Cha*_*adD 22 .net vb.net generics nullable
我有以下VB.NET函数,例如:
Public Function MyFunction (Of TData) (ByVal InParam As Integer) As TData
End Sub
Run Code Online (Sandbox Code Playgroud)
我如何在函数中确定是否TData为NULLable类型?
Jon*_*eet 41
一种方法是:
If Nullable.GetUnderlyingType(GetType(TData)) <> Nothing
Run Code Online (Sandbox Code Playgroud)
......至少,C#是:
if (Nullable.GetUnderlyingType(typeof(TData)) != null)
Run Code Online (Sandbox Code Playgroud)
假设你在询问它是否是可以为空的值类型.如果你问的是它是可以为空的值类型还是类,那么C#版本将是:
if (default(TData) == null)
Run Code Online (Sandbox Code Playgroud)
但我不确定一个简单的VB翻译是否可以在那里工作,因为VB中的"Nothing"略有不同.
VB.net:
Dim hasNullableParameter As Boolean = _
obj.GetType.IsGenericType _
AndAlso _
obj.GetType.GetGenericTypeDefinition = GetType(Nullable(Of ))
Run Code Online (Sandbox Code Playgroud)
C#:
bool hasNullableParameter =
obj.GetType().IsGenericType &&
obj.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
Run Code Online (Sandbox Code Playgroud)