How to find out the type of a property if it is a collection in Reflection?

List<MyClass> MyClassPro { get;set; } MyClass obj = new MyClass(); obj.MyClassPro = null; 

Consider MyClassPro as NULL. In the Reflection situation, I will not know the class name or property name.

If I try to get a Property Type using GetType, for example,

  Type t = obj.GetType(); 

It returns "System.Collections.Generic.list". But I expect to get a type like MyClass.

I also tried how

  foreach(PropertyInfo propertyInfo in obj.GetProperties()) { if(propertyInfo.IsGenericType) { Type t = propertyInfo.GetValue(obj,null).GetType().GetGenericArguments().First(); } } 

But it returns an error due to the value of the collection property null, so we cannot get Type.

In this situation, I can get the collection property type.

Please help me!

Thanks at Advance.

+6
source share
2 answers

Use propertyInfo.PropertyType instead of propertyInfo.GetValue(obj,null).GetType() , which should provide you with the property type, even if the property value is null .

So, when you have a class like

 public class Foo { public List<string> MyProperty { get; set; } } 

and an instance of Foo in obj , then

 var propertyInfo = obj.GetType().GetProperty("MyProperty"); // or find it in a loop like in your own example var typeArg = propertyInfo.PropertyType.GetGenericArguments()[0]; 

will give you the value of System.String (as an instance of System.Type ) in typeArg .

+10
source

Use propertyInfo.PropertyType , which has a property named IsGenericType , for example:

 if (propertyInfo.PropertyType.IsGenericType) { // code ... } 
+6
source

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


All Articles