Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

inheritance - I can't access variable from base class c#

public class MyClass
{
    public int x;
}
public class MyClass2: MyClass
{
    x=1;    
}

I'm trying to access variable x from base class but I get an error saying that the name x does not exists in current context.

question from:https://stackoverflow.com/questions/65540635/i-cant-access-variable-from-base-class-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can access it from inside a method like this:

public class MyClass2: MyClass
{
    private void MyMethod()
    {
         x=1;
    }  
}

Or from a different class:

var test = new MyClass2();
test.x = 1;

If you intend for your x field to be public, you should consider changing it to a property and capitalizing it, like this:

public int X { get; set; }

You can read about the difference between fields and properties here. If you do make it a property, be sure to follow Microsoft design guidelines and use PascalCase. See here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...