我试图创建一些带有两个变量的类.其中一个变量是Name,另一个变量是Value.对于每个类,值可以是不同类型的变量(int、double或string).
我想把这些类的实例存储在一个列表中,所以我把这些类放在一个抽象类下.
然后在foreach循环中,我想使用这些实例的值,但我需要将它们转换为原始类型,以便参数.Set函数将接受它.
我的代码是这样的:
List<ElementProperty> parameters = new List<ElementProperty>();
//I add my parameters to the list.
parameters.Add(new ElementProperty.String("TestName", "TestVariable"));
parameters.Add(new ElementProperty.Integer("TestName", 10));
//I want to make this foreach loop shorter and more proper
foreach (var parameter in parameters)
{
Parameter param = el.LookupParameter(parameter.Name);
if (parameter is ElementProperty.Boolean)
{
param.Set(((ElementProperty.Boolean)parameter).Value);
//param.Set only accepts int double and string
}
else if (parameter is ElementProperty.Double)
{
param.Set(((ElementProperty.Double)parameter).Value);
}
else if (parameter is ElementProperty.Integer)
{
param.Set(((ElementProperty.Integer)parameter).Value);
}
else if (parameter is ElementProperty.String)
{
param.Set(((ElementProperty.String)parameter).Value);
}
}
public abstract class ElementProperty
{
public string Name;
public object Value;
public class Integer : ElementProperty
{
public new int Value;
public Integer(string Name, int Value)
{
this.Name = Name;
this.Value = Value;
}
}
public class Double : ElementProperty
{
public new double Value;
public Double(string Name, double Value)
{
this.Name = Name;
this.Value = Value;
}
}
public class String : ElementProperty
{
public new string Value;
public String(string Name, string Value)
{
this.Name = Name;
this.Value = Value;
}
}
public class Boolean : ElementProperty
{
public new int Value;
public Boolean(string Name, bool Value)
{
this.Name = Name;
if (Value is false)
{
this.Value = 0;
}
else
{
this.Value = 1;
}
}
}
}
有更好的 Select 吗?任何建议都会有很大帮助.