动态地将项目添加到List< T>中.通过反思 [英] Dynamically adding items to a List<T> through reflection

查看:47
本文介绍了动态地将项目添加到List< T>中.通过反思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说我上这堂课

class Child {
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class Container {
    public List<Child> { get; set; }
}

我正在研究一种反序列化器,我希望能够从检索到的数据中创建并填充Child列表.我已经走了这么远(在这个示例中,我已经为其他类型省去了很多处理,因此它不必要地笨拙",但请忍受):

I'm working on a deserializer of sorts and I want to be able to create and populate the Child list from the data retrieved. I've gotten this far (I've cut out a lot of handling for other types for this example so its unnecessarily "iffy" but bear with me):

var props = typeof(Container).GetProperties();

foreach (var prop in props) {
    var type = prop.PropertyType;
    var name = prop.Name;

    if (type.IsGenericType) {
        var t = type.GetGenericArguments()[0];

        if (type == typeof(List<>)) {
            var list = Activator.CreateInstance(type);
            var elements = GetElements();

            foreach (var element in elements) {
                var item = Activator.CreateInstance(t);
                Map(item, element); 

                // ??? how do I do list.Add(item) here?
            }

            prop.SetValue(x, list, null); // x is an instance of Container

        }
    }
}

我不知道如何将list强制转换为List<t.GetType()>,因此我可以访问add方法并添加项目.

I can't figure out how to cast list to essentially List<t.GetType()> so I can access the add method and add the item.

推荐答案

我想说您应该转换为System.Collections.IList并直接调用Add方法.优点:简单,没有丑陋的倒影.缺点:导致对包含值类型的列表进行装箱.

I would say you should cast down to System.Collections.IList and directly call the Add method. Pros: simple, no ugly reflection. Cons: causes boxing for Lists containing value types.

这篇关于动态地将项目添加到List&lt; T&gt;中.通过反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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