c#: how to convert string to custom template type (i.e. implement "T convertTo<T>(string)")
I want a function that can convert "string" to a given type T. I.e. I want to implement such function:
开发者_JAVA百科T convertTo<T>(string stringToConvert)
T could be actually either simple type or enum, but i don't know how to check actual T type at runtime. I.e. I can't write something like that:
if (T instanceof MyEnum) { return MyEnum.Parse(stringToConvert); }
How can I implement my function then?
return (T)Enum.Parse(typeof(T), stringToConvert);
if (typeof(T) == typeof(MyEnum))
return (T)Enum.Parse(typeof(T), stringToConvert);
finally I've implemented function this way:
private static T ConvertFromString<T>(string text)
{
if (typeof(Enum).IsAssignableFrom(typeof(T)))
{
try
{
return (T)Enum.Parse(typeof(T), text);
}
catch (ArgumentException e)
{
return default(T);
}
}
return (T)Convert.ChangeType(text, typeof(T));
}
精彩评论