C#比较本机类型和可空类型(Int32与Int32?)

Dre*_*reX 1 c# generics types nullable

有没有办法在C#中比较可空和非可空的泛型?

例如:

public void function<T>()
{
    Type t = sqlreader.GetValue(pos).GetType();
}
Run Code Online (Sandbox Code Playgroud)

哪里t是类型Int32T类型Nullable<Int32>.

我们如何比较tT返回true

Jon*_*eet 8

目前还不清楚你要做什么,但你可能只能使用Nullable.getUnderlyingType:

if (t == Nullable.GetUnderlyingType(typeof(T)))
Run Code Online (Sandbox Code Playgroud)


SLa*_*aks 6

打电话Nullable.GetUnderlyingType(t).
如果t是a Nullable<X>,这将返回typeof(X); 否则,它将返回null.

因此,你可以写

t = Nullable.GetUnderlyingType(t) ?? t;
Type bigT = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);

if (t == bigT) 
Run Code Online (Sandbox Code Playgroud)