开发者

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));
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜