这在.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
,并试图验证destinationType
is是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] 删除。
我来说两句