注意:我并不是要确定泛型参数是否可以为 null。我想知道的是,如果它是可为空的,那么可为空的基础类型是什么?
这是我正在尝试的:
Function CreateTdParameter(Of T)(Name As String, Value As T) As TdParameter
Dim TdType As TdType
Dim ValueType As Type = GetType(T)
If ValueType.IsGenericType Then
Dim GenType As Type = ValueType.GetGenericTypeDefinition()
If GenType = GetType(Nullable(Of )) Then
ValueType = Activator.CreateInstance(GenType.MakeGenericType(New Type() {ValueType}))
ValueType = Nullable.GetUnderlyingType(ValueType.GetGenericTypeDefinition().UnderlyingSystemType)
End If
End If
If ValueType = GetType(String) Then
TdType = Teradata.Client.Provider.TdType.VarChar
ElseIf ValueType = GetType(Integer) Then
TdType = Teradata.Client.Provider.TdType.Integer
ElseIf ValueType = GetType(DateTime) Then
TdType = Teradata.Client.Provider.TdType.Timestamp
Else
Throw New NotImplementedException(String.Format("{0} not expected.", Value.GetType))
End If
Return CreateTdParameter(Name, Value, TdType, ParameterDirection.Input)
End Function
当 DateTime?
通过 Value
参数传递时,会导致以下错误:
GenericArguments[0]、'System.Nullable
1[System.DateTime]',在 'System.Nullable1[T]' 上违反了类型 'T' 的约束。
看来我需要获取基础类型才能使用反射实例化该类型的可空对象。不确定如何绕过这个第 22 条军规。
任何人都可以指出一种方法来判断泛型类型是否可为空,如果是,我如何获取其基础类型?
最佳答案
我将使用 C# 作为示例:
Type underlyingType = Nullable.GetUnderlyingType(typeof(T));
if(underlyingType != null) {
.. is nullable, with underlying-type as described
}
关于.NET 4.0 : How can I get the underlying type of a generic parameter if it is Nullable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10536553/