How to use Reflection to set a property of type List <CustomClass>

There is already a similar question , but he did not seem to ask about the situation this question is talking about.

The user asked about custom classes in the list, but his list object has a type string.

I have a Foo class that has a list of bars:

    public class Foo : FooBase
    { 
       public List<Bar> bars {get; set;} 
       public Foo() {}
    }

    public class Bar
    {
       public byte Id { get; set; } 
       public byte Status { get; set; } 
       public byte Type { get; set; } 
       public Bar(){} 
    }

I create Foo using reflection through Activator.CreateInstance (). Now I need to populate this list of bars with Bar objects.

Foo is obtained using

Assembly.GetAssembly(FooBase).GetTypes().Where(type => type.IsSubclassOf(FooBase));

The bar is a public class in the same Assembly. I need to figure it out somehow. I don't seem to see what type of list is contained in Foo. I know this is a list. I see the list property as List`1.

, .

+3
2

List`1

- , , " 1 arg, aka List<>". PropertyInfo, ; List<Bar>. Bar ?

, , ; ( IList<T>, , , List<T>):

static Type GetListType(Type type) {
    foreach (Type intType in type.GetInterfaces()) {
        if (intType.IsGenericType
            && intType.GetGenericTypeDefinition() == typeof(IList<>)) {
            return intType.GetGenericArguments()[0];
        }
    }
    return null;
}
+3
var prop = footype.GetProperty("bars");
// In case you want to retrieve the time of item in the list (but actually you don't need it...)
//var typeArguments = prop.PropertyType.GetGenericArguments();
//var listItemType = typeArguments[0];
var lst = Activator.CreateInstance(prop.PropertyType);
prop.SetValue(foo, lst, null);
+2

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


All Articles