이것은 .NET Core 1.1.4 프로젝트 내에 있으므로이 점을 고려하십시오.'Nullable <T>'을 Type 매개 변수로 C# 함수에 전달
유형에 값을 할당 할 수 있는지 확인하는 함수를 만들려고 시도했지만 유형이 Nullable<T>
인 경우 문제가 발생합니다.
내 기능 :이 null
value
이고 destinationType
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
절 상기 경우를 처리; else
절은 value
에 실제로 내용이 포함되어있는 경우 처리하므로 사용자가 destinationType
에 할당 할 수 있는지 또는 Nullable<T>
인 경우 T
에 할당 할 수 있는지를 결정합니다.
문제는 Nullable<T>
이 Type
이 아니므로 CheckIfAssignable(3, Nullable<Int32>)
을 호출하는 것이 기능 서명과 일치하지 않는다는 것입니다. 나를 Nullable<T>
을 통과
protected void CheckIsAssignable(Object value, ValueType destinationType)
수 있지만 그때 Nullable.GetUnderlyingType
에 인수로 제출 할 수 없습니다
에 서명을 변경.
이 문제가 너무 복잡해 졌는지 확실하지 않지만 간단한 해결책이 있다고 생각합니다.
' Null 허용'다른 유형과 같은 유형이다 : 당신은 너무처럼
typeof()
명령을 사용해야합니다. 다른 타입과 마찬가지로'typeof()'를 사용하십시오. – SLaks