-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