2011-12-23 6 views
4

value-type、nullable value-type、enum、nullable-enum、リフレクションによる参照型の区別方法を教えてください。value-type、nullable value-type、enum、nullable-enum、リフレクションによる参照型を区別する方法は?

enum MyEnum 
    { 
     One, 
     Two, 
     Three 
    } 

    class MyClass 
    { 
     public int IntegerProp { get; set; } 
     public int? NullableIntegerProp { get; set; } 
     public MyEnum EnumProp { get; set; } 
     public MyEnum? NullableEnumProp { get; set; } 
     public MyClass ReferenceProp { get; set; } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      Type classType = typeof(MyClass); 

      PropertyInfo propInfoOne = classType.GetProperty("IntegerProp"); 
      PropertyInfo propInfoTwo = classType.GetProperty("NullableIntegerProp"); 
      PropertyInfo propInfoThree = classType.GetProperty("EnumProp"); 
      PropertyInfo propInfoFour = classType.GetProperty("NullableEnumProp"); 
      PropertyInfo propInfoFive = classType.GetProperty("ReferenceProp"); 

      propInfoOne.??? 
      ............... 
      ............... 
     } 
    } 

ここで、これらの情報は取得できますか?

+0

"基本タイプ"はどのように定義しますか? – CodesInChaos

+0

int、float、double ........ MyClass-propsでわかるように。値の型。 – anonymous

+0

カスタム構造体はどうですか?たとえば、列挙型を他の値型と区別する必要がある理由はわかりません。 – CodesInChaos

答えて

6

ここでは、enum、nullable、primitve、valueの各タイプのチェック方法を示します。

Console.WriteLine(propInfoOne.PropertyType.IsPrimitive); //true 
Console.WriteLine(propInfoOne.PropertyType.IsValueType); //false, value types are structs 

Console.WriteLine(propInfoThree.PropertyType.IsEnum); //true 

var nullableType = typeof (Nullable<>).MakeGenericType(propInfoThree.PropertyType); 
Console.WriteLine(nullableType.IsAssignableFrom(propInfoThree.PropertyType)); //true 

値型とプリミティブは異なるものです。プリミティブは型にマッピングされる単なる省略表現です(例:bool> System.Boolean)。値の型は値によって渡されます。それらはクラスではなく構造体です。

+0

「基本」とは、基本的な価値タイプを意味します。 – anonymous

+0

タイプが「プリミティブ」かどうかを示すために、リフレクションを介して利用できるものはありません。この概念はCLRでは実際には存在しません。なぜなら、他の値型とは異なる型を扱わないからです。他の値型とは違って考慮する型のリストがある場合は、そのリストを維持して、それらの型を明示的に探してください。 –

+1

@Programming Hero:Type.IsPrimitiveプロパティが示していることを教えてください。 –

0

PropertyType.Nameは、Nullable型とNullable型の出力が異なるようです。これはあなたに少し助けになるかもしれません。

実際はにNullableと1のInt32を出力します。

2
public void Test(Type desiredType, object value) 
    { 
     if (desiredType.IsGenericType) 
     { 
      if (desiredType.GetGenericTypeDefinition() == typeof(Nullable<>)) 
      { 
       if (value == null) 
       { 
       } 
      } 
     } 
    } 
関連する問題