将Nullable <T>作为类型参数传递给C#函数

Taserian

这在.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);
            }
        }
    }

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

问题是Nullable<T>不是Type,因此调用CheckIfAssignable(3, Nullable<Int32>)与函数签名不匹配。

将签名更改为:

protected void CheckIsAssignable(Object value, ValueType destinationType)

让我传递了一个Nullable<T>,但是我不能将它作为参数提交给Nullable.GetUnderlyingType

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

大卫·沃茨

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

CheckIfAssignable(3, typeof(Nullable<Int32>))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将 httprequst 作为参数传递给函数 (C#)

MongoDB C#创建一个函数,我可以将类型/类名作为参数传递给它

C# 将 List<T> 中的对象作为参数传递

在将类型或名称空间名称“ T”作为参数传递给MVC Controller时找不到

将类类型作为参数传递给类构造函数

如何将类类型作为参数传递给函数?

将`struct`作为类型名称传递给函数参数

将数据类型作为参数传递给函数

将_bstr_t对象传递给以BSTR作为参数的函数是否安全?

有什么方法可以将未知类型的数组作为参数传递给C中的函数?

将Java脚本函数作为参数传递给C ++函数

从C#将表类型对象作为输入参数传递给Oracle中的存储过程

如何将C#对象作为参数传递给Javascript函数

将ServiceClientCredentials作为参数传递给C#中的构造函数

我无法将数组作为参数传递给 C# 中的函数

C# 如何将通用类型的枚举作为变量传递给函数...?

C#-如何将List <T>作为参数传递给委托

将函数作为参数传递给函数

C ++-将Rapidjson :: Document作为参数传递给函数

将Cython类对象作为参数传递给C函数

C++:将未知联合传递给函数作为参数

将数组作为参数传递给C函数

将指针传递给char数组作为函数的参数-C

C - 将 argv[x] 作为 wchar_t 传递给函数

将枚举作为参数传递给 C# 中的方法

将谓词作为参数传递给C#

如何将 LIST<T> 作为消息传递给 c# 中的 pubsub

如果传递的函数也将函数作为参数,如何将函数作为参数传递给C中的函数?

将Arraylist作为参数传递给函数