-1
我有兩個繼承的類。這些類有一些靜態變量。我想要做的是,我想將對象的值設置爲其子類名稱,並用父對象調用子類方法。以下是示例代碼:將變量的值設置爲類名
class BlueSwitch : Switch {
public static string Foo = "bar";
}
class Green : Switch {
public static string Foo = "bar2";
}
Switch oSwitch = BlueSwitch;
Console.WriteLine(oSwitch.Foo); // should print out "bar" but instead i get compiler error
oSwitch = GreenSwitch;
Console.WriteLine(oSwitch.Foo); // should print out "bar2" but instead i get compiler error
任何其他想法我該如何做到這一點?
'Switch oSwitch = BlueSwitch;'不會編譯。您必須創建一個實例,如'Switch oSwitch = new BlueSwitch();' – RafaelC
要通過您的類的實例調用,您必須「new」一個實例,然後在這些類中定義只讀實例屬性,值。但是,爲什麼不通過靜態的'BlueSwitch.Foo'來調用呢?另外一個不好的主意是公開一個像這樣的靜態字段,因爲它不是隻讀的,並且可以被任何人改變 – pinkfloydx33