如何使用Reflection设置类型为List <customclass> </customclass>的Property

时间:2009-08-21 14:17:40

标签: c# reflection .net-2.0

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

用户询问列表中的自定义类,但他的列表对象是string类型。

我有一个Foo类,它有一个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(){} 
    }

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

使用

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

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

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

2 个答案:

答案 0 :(得分:3)

文字

List`1

是在bonnet下编写泛型的方式 - 意思是“List with 1 generic type arg,aka List<>”。如果您有PropertyInfo,则应该设置;这将是封闭的通用List<Bar>。您是否希望找到Bar 这个?

如果是这样,会在各种问题中讨论,包括this one;复制密钥位(我更喜欢针对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;
}

答案 1 :(得分:2)

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