2016-09-11 172 views
-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 

任何其他想法我該如何做到這一點?

+1

'Switch oSwitch = BlueSwitch;'不會編譯。您必須創建一個實例,如'Switch oSwitch = new BlueSwitch();' – RafaelC

+0

要通過您的類的實例調用,您必須「new」一個實例,然後在這些類中定義只讀實例屬性,值。但是,爲什麼不通過靜態的'BlueSwitch.Foo'來調用呢?另外一個不好的主意是公開一個像這樣的靜態字段,因爲它不是隻讀的,並且可以被任何人改變 – pinkfloydx33

回答

2

你在這裏做什麼是非常不合邏輯的。您正在調整變量oSwitch的類名。這是不可能的。

你應該做的是:

Switch oSwitch = new BlueSwitch(); 
// this will print bar 
oSwitch = new GreenSwitch(); 
// this will print bar2 

旁註

你的領域是靜態的,而你的變量oSwitch開關類型。如果你想要做正確的事情,要麼使你的類領域的公共領域(這也是壞的),並刪除這將給你這個靜態的東西:

class BlueSwitch : Switch { 
    public string Foo = "bar"; 
} 

class Green : Switch { 
    public string Foo = "bar2"; 
} 

或者你可以讓他們留下靜態的,而是你的代碼將變成

string test = BlueSwitch.Foo; 
// writes bar 
test = GreenSwitch.Foo; 
// writes bar2