简体   繁体   中英

How do I use Reflection to set a Property with a type of List<CustomClass>

There is already a similar question but it didn't seem to ask about the situation that the question implies.

The user asked about custom classes in a list but his list object is of type string.

I have a class Foo 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 instantiate Foo using reflection via Activator.CreateInstance(). Now I need to populate that list of bars with Bar objects.

Foo is obtained using

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

Bar is a public class in the same Assembly. I'll need to get at that type somehow. I can't seem to see what the type of the list contained in Foo is. I know it's a list though. I'm seeing the list property as List`1.

I'd need to see what type of object the list holds and handle that accordingly.

The text

List`1

is the way that generics are written under the bonnet - meaning "List with 1 generic type arg, aka List<> ". If you have a PropertyInfo , you should be set; this will be the closed generic List<Bar> . Is it that you want to find the Bar given just this?

If so, this is discussed in various questions, including this one ; to duplicate the key bit (I prefer to code against IList<T> , since it handles a few edge-cases such as inheriting from 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;
}
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM