C# 使用反射设置类型为 List<CustomClass> 的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/315231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 22:52:12  来源:igfitidea点击:

Using Reflection to set a Property with a type of List<CustomClass>

c#reflection.net-2.0

提问by dragonjujo

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?

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

Edit:

编辑:

I should have specified that the object is more like this, but Marc Gravell's answer works still.

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

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

采纳答案by Marc Gravell

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

回答by Neil

Here's an example of taking the List<> type and turning it into List<string>.

下面是一个将 List<> 类型转换为 List<string> 的示例。

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

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