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

dra*_*ujo 14 c# reflection .net-2.0

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

编辑:

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

class Foo
{
    public List<string> Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 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);
    }
}
Run Code Online (Sandbox Code Playgroud)