我有一个基类,如下所示
public class base
{
public int x;
public void adjust()
{
t = x*5;
}
}
和一个派生自它的类。我可以在派生类的构造函数中设置x的值,并期望adjust()
函数使用该值吗?
答案 0 :(得分:9)
是的,这应该完全按预期工作,即使您的代码示例不太合理(什么是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
有一点需要注意的是,如果在x
构造函数中使用Base
,则在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
将为7
和Base
返回Derived
。
答案 1 :(得分:2)
是的,它应该有用。
以下略微修改代码将打印'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));
}
}