I came across a lot of code in our company codebase with the following structure
class Base
{
public Base (var a, var b)
{
base_a = a;
base_b = b;
}
var base_a;
var base_b;
}
class Derived:Base
{
publc Derived (var a,b,c,d): base (a,d)
{
der_c = c;
der_d = d;
}
var der_c;
var der_d;
var der_e;
}
class Ref
{
Base _ref;
public Ref(var a,b,c,d)
{
_ref = new Derived (a,b,c,d)
}
public void method()
{
_ref.der_e = 444; // won't compile
}
}
什麼是初始化der_e的正確方法?引用基類併爲_ref使用對象派生類有什麼好處?只是使用基類引用可以容納多個派生類對象的事實?如果是這樣的話,派生類的所有成員變量都應該在構造過程中初始化(像這樣:_ref = new Derived(a,b,c,d))。如果我想稍後在方法中初始化_ref.der_e怎麼辦?我知道我可以做到這一點(var cast_ref = _ref爲Derived; cast_ref.der_e = 444),但這種看起來並不是最佳做法。擁有這樣一個結構的想法是什麼,以及在派生類對象構建之後初始化其成員的正確性是什麼?使用基類引用對象初始化派生類成員變量
你給不會在所有的編譯代碼 - 你不能使用'var'參數或字段(除非實際上有一個名爲'var'的類)。請給出一個*逼真的例子 - 理想情況下更短,遵循.NET命名約定,並且格式更好。 –