【发布时间】:2017-10-09 20:46:13
【问题描述】:
我想用一行代码而不是 switch case 生成正确的对象,因为总是在添加新设备时我必须添加新行。
是否可以在没有开关盒的情况下在一行中做到这一点?
public static Device GetDevice(Device.enumDevice TypeOfDevice, string alias)
{
// Create the Object with using reflection
switch (TypeOfDevice)
{
case Device.enumDevice.A34411:
return new A34411(string alias);
break;
case Device.enumDevice.N5744:
return new N5744(string alias);
break;
default:
throw new NotImplementedException();
}
return null;
}
【问题讨论】:
-
您可以在类上放置自定义属性并使用反射,枚举
Device基类的所有子类,寻找具有正确值的属性。 -
所以你的计划是也删除枚举的使用?
-
return new A34411(string alias);这个语法不正确。删除string。 -
另外,最后的
return null是无用的,因为无法访问。所有可能的路径都以 switch 的一个分支结束,每个分支都返回或抛出异常。
标签: c#