How to split between values, null values, enumerations, enumerables, nullable-enum, reference types through reflection?

How to distinguish values โ€‹โ€‹of type value, nullable value-type, enum, nullable-enum, reference-types through reflection?

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.??? ............... ............... } } 

Where in propInfo ... can this data be obtained?

+4
source share
3 answers

This is how you check the enum types, nullable, primitve and 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 

Note that value types and primitives are two different things. Primitives are simply shorthands that map to types (e.g. bool> System.Boolean). Value types are passed by value; they are struct (ure) s not classes.

+6
source
  public void Test(Type desiredType, object value) { if (desiredType.IsGenericType) { if (desiredType.GetGenericTypeDefinition() == typeof(Nullable<>)) { if (value == null) { } } } } 
+2
source

PropertyType.Name seems to give different output for the Non Nullable and Nullable types. Maybe this can help you.

In fact, it gives Nullable`1 Int32 as output for Nullable and Non nullable.

0
source

Source: https://habr.com/ru/post/1387715/


All Articles