开发者

C# Inheritance : modify base class variable from derived class

I have a base class that 开发者_Go百科looks as follows

public class base 
{
      public int x;
      public void adjust()
      {
           t = x*5;
      }
}

and a class deriving from it. Can I set x's value in the derived class's constructor and expect the adjust() function to use that value?


Yes, that should work entirely as expected, even though your code sample does not quite make sense (what is t?). Let me provide a different example

class Base
{
    public int x = 3;
    public int GetValue() { return x * 5; }
}
class Derived : Base
{
    public Derived()
    {
        x = 4;
    }
}

If we use Base:

var b = new Base();
Console.WriteLine(b.GetValue()); // prints 15

...and if we use Derived:

var d = new Derived();
Console.WriteLine(d.GetValue()); // prints 20

One thing to note though is that if x is used in the Base constructor, setting it in the Derived constructor will have no effect:

class Base
{
    public int x = 3;
    private int xAndFour;
    public Base()
    {
        xAndFour = x + 4;
    }
    public int GetValue() { return xAndFour; }
}
class Derived : Base
{
    public Derived()
    {
        x = 4;
    }
}

In the above code sample, GetValue will return 7 for both Base and Derived.


Yes, it should work.

The following, slightly modified code will print 'Please, tell me the answer to life, the universe and everything!' 'Yeah, why not. Here you go: 42'

public class Derived : Base
{
    public Derived()
    {
        x = 7;
    }
}

public class Base
{
    public int x;
    public int t;
    public void adjust()
    {
        t = x * 6;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Base a = new Derived();
        a.adjust();

        Console.WriteLine(string.Format("'Please, tell me the answer to life, the universe and everything!' 'Yeah, why not. Here you go: {0}", a.t));
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜