如何解决此问题,以将其通用转换为Nullable< T> ;?

如何解决此问题,以将其通用转换为Nullable< T> ;?

问题描述:

我目前使用这种方便的转换扩展方法在类型之间进行转换:

I currently use this handy conversion extension method to do conversions between types:

    public static T To<T>(this IConvertible obj)
    {
        return (T)Convert.ChangeType(obj, typeof(T));
    }

但是,它不喜欢将有效值转换为Nullable,例如,这会失败:

However, it doesn't like converting valid values to Nullable, for example, this fails:

    "1".To<int?>();

显然,很容易将1转换为(int?),但是会出现错误:

Obviously, 1 is easily converted to an (int?), but it gets the error:

    Invalid cast from 'System.String' to 'System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

这是一个明显简化的示例,实际上我正在使用它来进行类似字符串类型的转换因此:

This is an obviously simplified example, in reality I'm using it to do conversions from string types like so:

packageDb.Quantity = package.package.ElementDeep(Namespace + "PackageQuantity", Namespace + "ActualQuantity", Namespace + "Quantity").ValueOrNull().To<int?>();

如果Convert.ChangeType不喜欢Nullable,那么有人有什么好主意吗?

If Convert.ChangeType doesn't like Nullable, anyone have any great ideas?

public static T To<T>(this IConvertible obj)
{
    Type t = typeof(T);
    Type u = Nullable.GetUnderlyingType(t);

    if (u != null)
    {
        return (obj == null) ? default(T) : (T)Convert.ChangeType(obj, u);
    }
    else
    {
        return (T)Convert.ChangeType(obj, t);
    }
}