【问题标题】:Using Reflection to set a Property with a type of List<CustomClass>使用反射设置 List<CustomClass> 类型的属性
【发布时间】:2008-11-24 19:52:16
【问题描述】:

如何使用反射来创建具有自定义类 (List) 的通用列表?我需要能够添加值和使用 propertyInfo.SetValue(..., ..., ...) 存储它。将这些 List 存储为其他数据结构会更好吗?

编辑:

我应该指定对象更像这样,但 Marc Gravell 的回答仍然有效。

class Foo
{
    public List<string> Bar { get; set; }
}

【问题讨论】:

  • 字符串真的是自定义类吗?我希望你会谈论类似使用反射来调用具有 List 属性的类 MyClass 之类的东西,其中 SomeOtherClass 是我创建的具有一堆属性和构造函数等的类...跨度>
  • 好的,所以字符串对于一个类来说是一个糟糕的选择,但它足以作为解释。就我有限的知识而言,几乎可以用任何类替换字符串,但在我要求的情况下,列表中的类和类型只能通过反射找到。

标签: c# reflection .net-2.0


【解决方案1】:
class Foo
{
    public string Bar { get; set; }
}
class Program
{
    static void Main()
    {
        Type type = typeof(Foo); // possibly from a string
        IList list = (IList) Activator.CreateInstance(
            typeof(List<>).MakeGenericType(type));

        object obj = Activator.CreateInstance(type);
        type.GetProperty("Bar").SetValue(obj, "abc", null);
        list.Add(obj);
    }
}

【讨论】:

  • 如果我有类 Foo{ public List 条 {get;设置;} } 类栏{ 公共字节 ID { 获取;放; } 公共字节状态 { 获取;放; } 公共字节类型 { 获取;放; } public Bar(){} } 我使用反射 activator.createinstance() 实例化 foo。现在我需要用 Bar 对象填充该条形列表。
  • 你那里的代码应该编译吗?有人告诉我,我仍然需要为 IList 的声明提供一个类型... IList 什么的,我不知道?
  • 我可以做 var list = Activator.CreateInstance(typeof(List).MakeGenericType(GetListType(p.ParameterType)));但我似乎没有得到一个列表作为回报,因为列表似乎没有 Add 方法......
  • 缺少使用 system.collection;
  • 为简洁起见,省略using 声明的情况并不少见。
【解决方案2】:

这是一个将 List 类型转换为 List 的示例。

var list = typeof(List).MakeGenericType(typeof(string));

【讨论】:

  • 这并没有给你任何类型的列表 - 它给你一个类型
猜你喜欢
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
相关资源
最近更新 更多