如何动态设置泛型类型?

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

        }

最佳答案

要在“常规”c# 中执行,您将使用反射来获取 MethodInfo,然后使用 MakeGenericMethod() 和 Invoke()。但是,这更容易:

Foo((dynamic)testObj);

这里的反射方法是:
var method = typeof(Class1).GetMethod("Foo").MakeGenericMethod(argType);
method.Invoke(this, new object[] { testObj });

关于c# - 转换为具有动态类型的集合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6971395/

10-11 01:52
查看更多