如何将值从对象转换为Nullable <>

Vit*_*one 6 c#

我有一些带有某些属性的类,我想将值从字符串转换为此属性的类型。而且我有转换为可为空类型的问题。这是我的转换方法:

public static object ChangeType(object value, Type type)
{
    if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
        if (value == null)
        {
            return null;
        }

        var underlyingType = Nullable.GetUnderlyingType(type);
        var val = Convert.ChangeType(value, underlyingType);
        var nullableVal = Convert.ChangeType(val, type); // <-- Exception here
        return nullableVal;
    }

    return Convert.ChangeType(value, type);
}
Run Code Online (Sandbox Code Playgroud)

我收到这样的异常(对于int类型的属性?):

从'System.Int32'到'System.Nullable`1 [[System.Int32,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]的无效转换。

如何从类型转换为可为空的类型?谢谢。

xan*_*tos 5

这是不可能的。值类型的装箱“擦除”该Nullable<>部分...

int? num = 5;
object obj = num;
Console.WriteLine(obj.GetType()); // System.Int32
Run Code Online (Sandbox Code Playgroud)

和

int? num = null;
object obj = num;
Console.WriteLine(obj == null); // True
Run Code Online (Sandbox Code Playgroud)

请注意,此特征是使Nullable<>“特殊” 成为特征的原因。他们需要CLR的直接支持。Nullable<>不仅仅是您可以编写的结构。

你可以做什么:

public static object ChangeType(object value, Type type)
{
    // returns null for non-nullable types
    Type type2 = Nullable.GetUnderlyingType(type);

    if (type2 != null)
    {
        if (value == null)
        {
            return null;
        }

        type = type2;
    }

    return Convert.ChangeType(value, type);
}
Run Code Online (Sandbox Code Playgroud)


Wil*_*ode 2

var nullableVal = Activator.CreateInstance(type, val);
Run Code Online (Sandbox Code Playgroud)

使用激活器将允许您创建该类的新实例int?,并将参数传递给该int值的构造函数。下面的代码是这样的字面演示:

var type = typeof(int?);

var underlyingType = typeof(int);

var val = 123;

var nullableVal = Activator.CreateInstance(type, val);
Run Code Online (Sandbox Code Playgroud)