我有一个基类,如下所示:
public class base
{
public int x;
public void adjust()
{
t = x*5;
}
}
还有一个从该类派生的类。我能在派生类的构造函数中设置x的值并期望adjust()
函数使用该值吗?
我有一个基类,如下所示:
public class base
{
public int x;
public void adjust()
{
t = x*5;
}
}
还有一个从该类派生的类。我能在派生类的构造函数中设置x的值并期望adjust()
函数使用该值吗?
是的,那应该完全按预期工作,即使你的代码示例不太合理(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
对于 Base
和 Derived
都会返回 7
。是的,它应该可以工作。
以下经过略微修改的代码将打印'请告诉我生命、宇宙和万物的答案!' '好的,为什么不呢。这是你要的答案: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));
}
}
adjust
。考虑发布你尝试过的代码。 - Snowbear