c#比较原生类型和可空类型(Int32和Int32?)
本文关键字:Int32 类型 比较 原生 | 更新日期: 2023-09-27 18:02:58
在c#中有没有比较可空型和非可空型的方法?
例如:public void function<T>()
{
Type t = sqlreader.GetValue(pos).GetType();
}
其中t
为Int32
型,T
为Nullable<Int32>
型。
如何比较t
和T
,使其返回true
?
这是相当不清楚你想做什么,但你可能能够使用Nullable.getUnderlyingType
:
if (t == Nullable.GetUnderlyingType(typeof(T)))
呼叫Nullable.GetUnderlyingType(t)
。
如果t
是Nullable<X>
,这将返回typeof(X)
;否则,返回null
。
因此,你可以写
t = Nullable.GetUnderlyingType(t) ?? t;
Type bigT = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
if (t == bigT)