Romainの正解に加えて、「実際の」型を比較したい場合(つまり、null許容型をその基になる型に暗黙的に変換せずに)、次のような拡張メソッドを作成できます。
public static class MyExtensionMethods
{
public static Type GetRealType<T>(this T source)
{
return typeof(T);
}
}
次に、次のテストを試してください。
int? a = 0;
Console.WriteLine(a.GetRealType() == typeof(int?)); // True
Console.WriteLine(a.GetRealType() == typeof(int)); // False
int b = 0;
Console.WriteLine(b.GetRealType() == typeof(int)); // True
Console.WriteLine(b.GetRealType() == typeof(int?)); // False
DateTime? c = DateTime.Now;
Console.WriteLine(c.GetRealType() == typeof(DateTime?)); // True
Console.WriteLine(c.GetRealType() == typeof(DateTime)); // False
DateTime d = DateTime.Now;
Console.WriteLine(d.GetRealType() == typeof(DateTime)); // True
Console.WriteLine(d.GetRealType() == typeof(DateTime?)); // False
編集...
完全を期すために(そして以下のSLaksのコメントによって促されます)、これsourceは、がnullまたはNullable<>;の場合にのみコンパイル時タイプを使用する代替バージョンです。それ以外の場合GetTypeは、ランタイムタイプを使用して返します。
public static class MyExtensionMethods
{
public static Type GetRealType<T>(this T source)
{
Type t = typeof(T);
if ((source == null) || (Nullable.GetUnderlyingType(t) != null))
return t;
return source.GetType();
}
}