0
有一個XML格式它說是這樣的:存儲在一個字符串指定的類型的屬性
<ExtraFields>
<ExtraField Type="Int">
<Key>Mileage</Key>
<Value>500000 </Value>
</ExtraField>
<ExtraField Type="String">
<Key>CarModel</Key>
<Value>BMW</Value>
</ExtraField>
<ExtraField Type="Bool">
<Key>HasAbs</Key>
<Value>True</Value>
</ExtraField>
</ExtraFields>
我要存儲在類此信息,我想它的字段設置爲指定類型的。我想到了一個通用的方法
static class Consts
{
public const string Int32Type = "int32";
public const string StringType = "string";
public const string BoolType = "bool";
}
public class ExtraFieldValue<TValue>
{
public string Key;
public TValue Value;public static ExtraFieldValue<TValue> CreateExtraField(string strType, string strValue, string strKey)
{
IDictionary<string, Func<string, object>> valueConvertors = new Dictionary<string, Func<string, object>> {
{ Consts.Int32Type, value => Convert.ToInt32(value)},
{ Consts.StringType, value => Convert.ToString(value)},
{ Consts.BoolType, value => Convert.ToBoolean(value)}
};
if (!valueConvertors.ContainsKey(strType))
return null;
ExtraFieldValue<TValue> result = new ExtraFieldValue<TValue>
{
Key = strKey,
Value = (TValue)valueConvertors[strType](strValue)
};
return result;
}
}
,但這種方法的問題是,我需要ExtraFields名單和他們每個人都可以在列表中有不同的類型。
我只能想到兩個選項至今:
1)使用該領域的動態關鍵字,但這種做法似乎有利用領域的一個對象類型和鑄造它的極限
2)動態類型爲必要的類型。但無論如何,如果我需要一些對象特定的調用,我將不得不做一個靜態轉換。
我很樂意閱讀您的想法/建議