如何获取 Nullable<T> 实例的类型
How to get a Nullable<T> instance's type
如果我这样做:
Type type = typeof(Nullable<int>);
type
变量保存正确的 Nullable'1
类型。
但是,如果我尝试这样做:
Nullable<int> n = 2;
Type type = n.GetType();
type
最终持有 System.Int32
这是基础类型,但不是我所期望的。
如何获取 Nullable<>
实例的类型?
请记住,我不知道可空实例的基础类型,所以我无法调用 typeof
。
不优雅,但您可以将其包装在通用函数中:
public static void Main()
{
int? i = 2;
Console.WriteLine( type(i) );
}
public static Type type<T>( T x ) { return typeof(T); }
如果我这样做:
Type type = typeof(Nullable<int>);
type
变量保存正确的 Nullable'1
类型。
但是,如果我尝试这样做:
Nullable<int> n = 2;
Type type = n.GetType();
type
最终持有 System.Int32
这是基础类型,但不是我所期望的。
如何获取 Nullable<>
实例的类型?
请记住,我不知道可空实例的基础类型,所以我无法调用 typeof
。
不优雅,但您可以将其包装在通用函数中:
public static void Main()
{
int? i = 2;
Console.WriteLine( type(i) );
}
public static Type type<T>( T x ) { return typeof(T); }