我正在嘗試創建一些帶有兩個變數的類。其中一個變數是名稱,另一個是值。每個類的值可以是不同型別的變數(int、double 或 string)。
我想將這些類的實體存盤在一個串列中,所以我將這些類放在一個抽象類下。
然后在 foreach 回圈中,我想使用這些實體的值,但我需要將它們轉換為原始型別,以便 param.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;
}
}
}
}
有更好的選擇嗎?任何建議都會有很大幫助。謝謝你。
uj5u.com熱心網友回復:
我更喜歡為此使用介面,但您可以執行以下操作:
// ...
foreach (var parameter in parameters)
{
parameter.SetTo(param); // Call same interface
}
// ...
在每個具體類中:
public class Integer : ElementProperty
{
public new int Value;
public Integer(string Name, int Value)
{
this.Name = Name;
this.Value = Value;
}
public void SetTo(Parameter p)
{
p.Set(this.Value); // calls correct overload
}
}
這完全可以在沒有 switch/case 或 if/else 鏈的情況下作業。
但是,請注意,使用這種模式的沖動可能暗示了潛在的設計問題。這就是它有時被視為“代碼氣味”的原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478363.html
