如何使用Reflection设置类型为List 的Property

已经存在类似的问题,但它似乎没有询问问题所暗示的情况。

用户询问列表中的自定义类,但其列表对象的类型为字符串。

我有一个类Foo,它有一个Bars列表:

public class Foo : FooBase { public List 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(){} } 

我通过Activator.CreateInstance()使用reflection实例化Foo。 现在我需要使用Bar对象填充该条形列表。

Foo是使用获得的

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

酒吧是同一个大会的公共课。 我需要以某种方式达到那种类型。 我似乎无法看到Foo中包含的列表类型是什么。 我知道这是一个清单。 我将list属性看作List`1。

我需要查看列表所包含的对象类型并相应地处理它。

文本

 List`1 

是generics在bonnet下编写的方式 – 意思是“List with 1 generic type arg,aka List<> ”。 如果您有PropertyInfo ,则应该设置; 这将是封闭的通用List 。 是不是你想找到这个Bar

如果是这样,这将在各种问题中讨论,包括这个问题; 复制密钥位(我更喜欢对IList进行编码,因为它处理一些边缘情况,例如inheritanceList ):

 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);