【发布时间】:2017-03-22 07:52:42
【问题描述】:
我正在尝试找到一种方法来在实例化具有不同属性的对象期间实现类似 switch case 的行为。
我的对象是这样的
class FooProperty
{
Nullable<int> IntergerValue {get; set;}
Nullable<bool> BoolValue {get; set;}
Nullable<float> FloatValue {get; set;}
string StringValue {get; set;}
}
我需要基于将类型映射到属性的整数来实例化我的类的实例 - 我正在设计的实例化函数如下所示:
public void Instantiate(int mappingKey, object value)
{
//Instantiate either interger, bool, float or string based on mappingKey
}
这里的关键是我不想要制作这样的开关盒
switch(mappingKey)
{
case 1:
new FooProperty
{
IntergetValue = (int) value
};
break;
case 2:
//BoolValue etc.
}
由于大量的代码重复。我认为必须有一种更聪明的方法来决定要实例化哪个属性,而无需每次都重复对象实例化。
【问题讨论】:
标签: c# generics instantiation