将`Nullable <T>`作为Type参数传递给C#函数

tas*_*ian 5 c# nullable .net-core

这是在.NET Core 1.1.4项目中,因此请考虑这一点.

我正在尝试创建一个函数来验证是否可以将值分配给某个类型,但我遇到了Nullable<T>类型问题.

我的功能:

    protected void CheckIsAssignable(Object value, Type destinationType)
    {
        if (value == null)
        {
            // Nullable.GetUnderlyingType returns null for non-nullable types.
            if (Nullable.GetUnderlyingType(destinationType) == null)
            {
                var message =
                    String.Format(
                        "Property Type mismatch. Tried to assign null to type {0}",
                        destinationType.FullName
                    );
                throw new TargetException(message);
            }
        }
        else
        {
            // If destinationType is nullable, we want to determine if
            // the underlying type can store the value.
            if (Nullable.GetUnderlyingType(destinationType) != null)
            {
                // Remove the Nullable<T> wrapper
                destinationType = Nullable.GetUnderlyingType(destinationType);
            }
            // We can now verify assignability with a non-null value.
            if (!destinationType.GetTypeInfo().IsAssignableFrom(value.GetType()))
            {
                var message =
                    String.Format(
                        "Tried to assign {0} of type {1} to type {2}",
                        value,
                        value.GetType().FullName,
                        destinationType.FullName
                    );
                throw new TargetException(message);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

if如果valuenull,则上面的子句处理该情况,并尝试验证destinationType是否Nullable<T>; else如果value实际包含某些内容,则该子句处理,因此它会尝试确定是否可以将其分配给,destinationType或者如果它是a Nullable<T>,则可以将其分配给T.

问题是Nullable<T>不是a Type,所以调用CheckIfAssignable(3, Nullable<Int32>)与函数签名不匹配.

将签名更改为:

protected void CheckIsAssignable(Object value, ValueType destinationType)
Run Code Online (Sandbox Code Playgroud)

让我通过一个Nullable<T>,但后来我不能把它作为参数提交Nullable.GetUnderlyingType.

我不确定我是否过度复杂了这个问题,但我觉得有一个简单的解决方案,我只是没有看到.

Dav*_*tts 6

你没有在那里传递类型.您需要typeof()像这样使用命令:

CheckIfAssignable(3, typeof(Nullable<Int32>))
Run Code Online (Sandbox Code Playgroud)