次のような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のリストが必要であり、それぞれがリスト内で異なるタイプを持つ可能性があることです。
これまでのところ、2つのオプションしか考えられません。
1)このフィールドに動的キーワードを使用しますが、このアプローチには制限があるようです
2)フィールドにオブジェクトタイプを使用し、その動的タイプを必要なタイプにキャストします。しかし、とにかく、オブジェクト固有の呼び出しが必要な場合は、静的キャストを行う必要があります。
私はあなたの考え/提案を読んでうれしいです