使用反射来设置与类型列表℃的属性; CustomClass> [英] Using Reflection to set a Property with a type of List<CustomClass>

查看:91
本文介绍了使用反射来设置与类型列表℃的属性; CustomClass>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用反射来创建一个自定义的类泛型列表(列表< CustomClass>)?我需要能够添加值并使用
propertyInfo.SetValue(...,...,...)储存。我会过得更好存储这些列表与LT;>的其他一些数据结构



编辑:



我应该指定的对象更像是这个,但是马克Gravell的答案工作仍在。

 类Foo 
{
公开名单<串GT;酒吧{搞定;组; }
}


解决方案

 类Foo 
{
公共字符串酒吧{搞定;组; }
}
类节目
{
静态无效的主要()
{$ B $型B型= ty​​peof运算(富); //可能从字符串
IList的名单=(IList的)Activator.CreateInstance(
的typeof(名单<>)MakeGenericType(类型)。);

obj对象= Activator.CreateInstance(类型);
type.GetProperty(酒吧)的SetValue(OBJ,ABC,NULL);
list.Add(OBJ);
}
}


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?

Edit:

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

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

这篇关于使用反射来设置与类型列表℃的属性; CustomClass&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆