Convert to a Nullable<T> from a string using Reflection

不羁岁月 提交于 2019-12-03 20:44:17

I would probably use the TypeConverter in this case, and Nullable.GetUnderlyingType(); example on the way...

    static void Main()
    {
        long? val1 = Parse<long?>("123");
        long? val2 = Parse<long?>(null);
    }

    static T Parse<T>(string value)
    {
        return (T) TypeDescriptor.GetConverter(typeof(T))
            .ConvertFrom(value);
    }

This should to the job. (Code is embedded in an extension method for simplicity, though it may not be what you want.)

public static T? ParseToNullable<T>(this string value) where T : struct
{
    var parseMethod = typeof(T).GetMethod("Parse", new Type[] { typeof(string) });
    if (parseMethod == null)
        return new Nullable<T>();

    try
    {
        var value = parseMethod.Invoke(null, new object[] { value.ToString() });
        return new Nullable<T>((T)value);
    }
    catch
    {
        return new Nullable<T>();
    }
}

Now, if you want the generic type paramter itself to be the nullable type rather than the underlying one (I don't really see an advantage in this), you can make use of:

Nullable.GetUnderlyingType(typeof(T))

as Marc Gravell suggested, and it would only require a few minor modifications to the code.

I added this little bit:

if (Nullable.GetUnderlyingType(t) != null)
{
    t = Nullable.GetUnderlyingType(t);
}

MethodInfo parse = t.GetMethod("Parse", new Type[] { typeof(string) });

Thanks everyone!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!