【发布时间】:2012-07-18 09:31:58
【问题描述】:
我想要一个在基类中定义的字段,它将影响属于该基类的对象的创建。但是,我希望能够覆盖字段的值,在基类 cto'r 被调用之前。一个例子:
class ObjNeedParam
{
public ObjNeedParam(int p)
{
val = p;
}
int val;
int Value{get{return Value;}}
}
class Base
{
public Base()
{
obj = new ObjNeedParam(paramVal);
}
ObjNeedParam obj;
protected int paramVal = 1;
}
class Derived : Base
{
public Derived()
{
//Once I'm here, obj has already been created with paramVal=1 instead of 2!
dummy = 3;
}
new int paramVal = 2;
int dummy;
}
【问题讨论】:
-
将 paramval 设为虚拟属性并覆盖它
-
您必须将值传递给基本构造函数
-
我理解问题和答案 - 我不明白的是 2 次投反对票...在这种情况下,你为什么要投反对票而不发表评论?
标签: c# inheritance field derived