English 中文(简体)
使用反射设置类型为List <CustomClass>的属性
原标题:
  • 时间:2008-11-24 19:52:16
  •  标签:

How can I use reflection to create a generic List with a custom class (List<CustomClass>)? I need to be able to add values and use propertyInfo.SetValue(..., ..., ...) to store it. Would I be better off storing these List<> s as some other data structure?

编辑:

我应该指明对象更像这样,但马克·格拉维尔的答案仍然有效。

class Foo
{
    public List<string> Bar { get; set; }
}
最佳回答
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);
    }
}
问题回答

这里是将 List<> 类型转换为 List<string> 的示例。

变量列表= typeof(List<>).MakeGenericType(typeof(string));





相关问题
热门标签