2016-09-11 43 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