Storing a property of the type specified in a string
There's an XML scheme which says something like this:
<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>
I want to store this info in the class and I want its field to be of the specified type. I thought of a generic approach
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 s开发者_如何转开发tatic 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;
}
}
But the problem with this approach is that I need a list of ExtraFields and each of them can have different type in a list.
I can only think of two options so far:
1) using a dynamic keyword for this field but this approach seems to have limits
2) using an object type for the field and casting its dynamic type to the necessary type. But anyhow if I will need some object specific calls, I will have to make a static cast.
I would be glad to read your thoughts/proposals
Just use a name/value collection. If you don't even know the property names until runtime, using dynamic
, or dynamically building a type at runtime isn't going to help you because you won't be able to write source that accesses those properties.
So, just use a name/value collection like something that implements IDictionary<string, object>
.
精彩评论