Ben*_*son 9 c# polymorphism compilation
以下代码工作正常:
ListControl lstMyControl;
if (SomeVariable == SomeEnum.Value1)
{
lstMyControl = new DropDownList();
}
else
{
lstMyControl = new RadioButtonList();
}
lstMyControl.CssClass = "SomeClass";
Run Code Online (Sandbox Code Playgroud)
以下代码无法编译:
ListControl lstMyControl;
switch (SomeVariable)
{
case SomeEnum.Value1:
lstMyControl = new DropDownList();
break;
case default:
lstMyControl = new RadioButtonList();
break;
}
lstMyControl.CssClass = "SomeClass";
Run Code Online (Sandbox Code Playgroud)
在第二个例子中,编译器说我正在尝试在尚未实例化的变量上设置属性.在任何一种情况下,必须实例化lstMyControl,但compilr似乎无法通过switch语句遵循该代码路径来查看.在上面的简单示例中,我将使用if/else.但是有几次我想用10个不同的类做这样的事情,这些类都继承自同一个基类,并且当一个switch语句是我应该使用的时候,有10个if/elseif语句很烦人.
Ear*_*rlz 17
ListControl lstMyControl;
switch (SomeVariable)
{
case SomeEnum.Value1:
lstMyControl = new DropDownList();
break;
default: //Don't prefix with "case"
lstMyControl = new RadioButtonList();
break;
}
lstMyControl.CssClass = "SomeClass";
Run Code Online (Sandbox Code Playgroud)