【问题标题】:How do I use Reflection to set a Property with a type of List<CustomClass>如何使用反射设置 List<CustomClass> 类型的属性
【发布时间】:2010-11-21 16:26:36
【问题描述】:

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

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

我有一个 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`1。

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

【问题讨论】:

  • 对不起,我错过了您在我之前的回复中添加的评论;如果您在短时间内添加了很多 cmets,那么那个危险的信封(屏幕顶部)并不总是很容易找到东西。

标签: c# reflection .net-2.0


【解决方案1】:
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】:

    正文

    List`1
    

    是泛型在引擎盖下编写的方式 - 意思是“具有 1 个泛型类型 arg 的列表,又名 List&lt;&gt;”。如果你有PropertyInfo,你应该设置;这将是封闭的通用List&lt;Bar&gt;。鉴于只是这个,你想找到Bar吗?

    如果是这样,这将在各种问题中进行讨论,包括this one;复制密钥位(我更喜欢针对IList&lt;T&gt; 进行编码,因为它处理一些边缘情况,例如从List&lt;T&gt; 继承):

    static Type GetListType(Type type) {
        foreach (Type intType in type.GetInterfaces()) {
            if (intType.IsGenericType
                && intType.GetGenericTypeDefinition() == typeof(IList<>)) {
                return intType.GetGenericArguments()[0];
            }
        }
        return null;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      相关资源
      最近更新 更多