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

时间:2008-11-24 19:52:16

标签: c# reflection .net-2.0

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

编辑:

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

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

2 个答案:

答案 0 :(得分:19)

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

答案 1 :(得分:1)

以下是获取List&lt;&gt;的示例输入并将其转换为List&lt; string&gt;。

var list = typeof(List&lt;&gt;)。MakeGenericType(typeof(string));

相关问题