动态创造的IList的类型的新实例实例、类型、动态、IList

2023-09-04 05:34:01 作者:〗鷡亽孒檞〖

我的申请正在处理IList中的。不同的用户定义类型的ILists。我想,我可以使用反射来看看IList中包含什么类型的对象,然后创建该类型的新实例,并随后添加到IList中本身?

My application is processing IList's. ILists of different user defined types. I'm thinking that i can use reflection to to see what type of object the IList contains and then create a new instance of that type and subsequently add that to the IList itself?

所以,在任何一个时间我可能会处理

So at any one time I might be processing

IList<Customer> l;

和我想创建客户的新实例

and I'd like to create a new instance of Customer

Customer c = new Customer(0, "None")

,然后添加到列表中。

and then add that onto the list

l.Add(c);

显然,在运行时动态地这样做,这是问题的症结所在。希望有人可以给我一些指点。感谢布兰登

Obviously doing this dynamically at run-time is the crux of the problem. Hope somebody can give me some pointers. Thanks brendan

推荐答案

试试这个:

    public static void AddNewElement<T>(IList<T> l, int i, string s)
    {
        T obj = (T)Activator.CreateInstance(typeof(T), new object[] { i, s });
        l.Add(obj);
    }

用法:

    IList<Customer> l = new List<Customer>();
    l.Add(new Customer(1,"Hi there ..."));

    AddNewElement(l, 0, "None");

(编辑):

试试这个话:

    public static void AddNewElement2(IList l, int i, string s)
    {
        if (l == null || l.Count == 0)
            throw new ArgumentNullException();
        object obj = Activator.CreateInstance(l[0].GetType(), new object[] { i, s });
        l.Add(obj);
    }