Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 强制转换到具有动态类型的集合_C#_Reflection - Fatal编程技术网

C# 强制转换到具有动态类型的集合

C# 强制转换到具有动态类型的集合,c#,reflection,C#,Reflection,如何动态设置泛型类型 public class A { public int X { get; set; } public A() { X = 9000; } } public class Class1 { public void Test() { List<A> theList = new List&

如何动态设置泛型类型

 public class A
    {
        public int X { get; set; }

        public A()
        {
            X = 9000;
        }
    }

    public class Class1
    {

        public void Test()
        {
            List<A> theList = new List<A>() {
                new A { X = 1 },
                new A { X = 2 }               
            };


            object testObj = theList;
            var argType = testObj.GetType().GetGenericArguments()[0];


            Foo(testObj as ICollection<argType>); // ?                                           

        }

        public void Foo<T>(ICollection<T> items) where T:new()
        {
            T newItem = new T();    
            items.Add(newItem);    

        }
公共A类
{
公共整数X{get;set;}
公共A()
{
X=9000;
}
}
公共班级1
{
公开无效测试()
{
列表列表=新列表(){
新的A{X=1},
新的A{X=2}
};
对象testObj=列表;
var argType=testObj.GetType().GetGenericArguments()[0];
Foo(testObj作为i集合);/?
}
公共void Foo(i集合项),其中T:new()
{
T newItem=newt();
项目。添加(新项目);
}
要在“常规”c中执行,您可以使用反射来获取MethodInfo,然后使用MakeGenericMethod()和Invoke()。但是,这更简单:

Foo((dynamic)testObj);
这里的反射方法是:

var method = typeof(Class1).GetMethod("Foo").MakeGenericMethod(argType);
method.Invoke(this, new object[] { testObj });

您不能这样做,因为在Foo函数中,您应该对集合执行一些操作,并且不能保证类型是安全的


唯一的方法是使用“对象”然后在Fooo函数中转换到适当的类型。

泛型不是这样工作的。BoltClock,应该怎么做?我应该注意,反射和泛型并不是最好的朋友……在许多方面,使用非泛型
IList
Marc给出的两种方法是很诱人的,一种是直接反射,另一种是wi动态打字。如果你认为这是不可能的,那就值得一提为什么你认为他的答案不起作用。没错。我在Marc的评论之前发表了我的评论。但是,我不知道反思的方式。我尽量避免,我也同意Marc的观点,泛型和反思很难共存。我提醒了一篇老文章在Bea Costa的作品中,她发明了一个可怕的技巧,使WPF能够在IEnumerable接口上正常工作。她不是Bea,而是反射表达式与泛型表达式的硬度。