创建使用反射泛型列表 [英] Create a generic list using reflection

查看:181
本文介绍了创建使用反射泛型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用反射来设置对象A从对象B.属性功能 在一个点上,我需要实例化一个泛型集合。但是,我无法得到它的工作。以下是我现在有:

I have a function that uses reflection to set properties of object A from object B. At one point, I need to instantiate a generic collection. However, I am unable to get it working. Here is what I have now:

IList list = destProperty.PropertyType.GetGenericTypeDefinition()
                .MakeGenericType(destProperty.PropertyType.GetGenericArguments())
                .GetConstructor(Type.EmptyTypes)
                .Invoke(null) as IList;

我想设置destProperty的价值。它必须是一个列表 在运行时,destProperty的类型的ICollection&LT的;>。我想,这是怎么回事是,因为ICollection的是一个接口,它没有构造函数。什么是正确的方式来实例化它呢?

I am trying to set the value of the destProperty. It has to be a List At runtime, the destProperty is of type ICollection<>. I think what's happening is that since ICollection is an interface, it has no constructor. What is the proper way to instantiate it then?

谢谢!

推荐答案

我重新写你的code,进入一个例子的形式(希望符合你想做什么!=),尝试更清楚的问题是什么:

I've re-written your code, into the form of an example (hopefully that matches what you're trying to do! =), to try and make it clearer what the problem is:

public class Program
{
    public struct MyType
    {
        public ICollection<string> MyProperty { get; set; }
    }
    static void Main(string[] args)
    {
        var type = typeof(MyType);
        var properties = type.GetProperties();
        var destProperty = properties[0];

        var genericTypeDefinition = destProperty.PropertyType.GetGenericTypeDefinition();
        var madeGenericType = genericTypeDefinition.MakeGenericType(destProperty.PropertyType.GetGenericArguments());
        var ctor = madeGenericType.GetConstructor(Type.EmptyTypes);
    }
}

如果你把一个断点上的倒数第二个括号,你会看到男星回来为,其中是因为,当你正确地推测,的ICollection&LT; T&GT; 没有任何构造函数,由于它是一个界面

If you put a breakpoint on the penultimate brace you'll see that ctor comes back as null, which is because, as you correctly surmised, ICollection<T> doesn't have any constructors due to it being an interface.

正因为如此,有这样做,因为没有固有的方式说不超通用的方式有什么的的ICollection&LT最好的执行情况; T&GT; 来使用在这种情况下。你需要做出决定和一,根据你反映回来的信息。

Because of this, there's no "super-generic" way of doing this because there's no inherent way to say "what's the best implementation of ICollection<T> to use in this situation". You'll need to make that decision and new one, based on the information you get back from reflection.

这篇关于创建使用反射泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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