C#继承:从派生类修改基类变量

5

我有一个基类,如下所示:

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

还有一个从该类派生的类。我能在派生类的构造函数中设置x的值并期望adjust()函数使用该值吗?


是的...值没有被设置。我认为我应该将它变成某种类型的变量以启用它。 - Aks
然后请展示您的完整代码。它“应该”可以工作,这意味着问题出在其他地方。 - Vilx-
好的,这意味着你做错了什么,因为它应该按照你的期望工作。除非你没有从基类构造函数中调用 adjust。考虑发布你尝试过的代码。 - Snowbear
好的。代码太多了,我会看看我做错了什么。谢谢你的帮助。 - Aks
2个回答

10

是的,那应该完全按预期工作,即使你的代码示例不太合理(t 是什么?)。让我提供一个不同的例子。

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

如果我们使用Base
var b = new Base();
Console.WriteLine(b.GetValue()); // prints 15

如果我们使用 Derived

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

需要注意的一点是,如果在Base构造函数中使用了x,那么在Derived构造函数中设置它将没有任何效果:

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;
    }
}

在上面的代码示例中,GetValue 对于 BaseDerived 都会返回 7

我刚刚编了一个例子来解释x正在基类函数中被使用的情况 :| - Aks

3

是的,它应该可以工作。

以下经过略微修改的代码将打印'请告诉我生命、宇宙和万物的答案!' '好的,为什么不呢。这是你要的答案: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));
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接