反射泛型

来源:互联网 发布:android获取网络时间 编辑:程序博客网 时间:2024/05/21 17:52

1.使用反射替换类型中方法的泛型 

//获取Apple<T>类型,`1作为泛型参数数目

 var type = Type.GetType("UnitTest.Apple`1");
//将Apple<T>中的泛型替换成指定的类型C
 var appleType = type.MakeGenericType(new[] { Type.GetType("UnitTest.C") });
 //生成Apple<T>实例
dynamic apple = Activator.CreateInstance(appleType);
 //调用GetInfo方法

 var list = apple.GetInfo();


namespace UnitTest
{

public class Apple<T> where T : new()
    {
        public List<T> GetInfo() 
        {
            List<T> list = new List<T>();
            T t1 = new T();
            list.Add(t1);
            return list;
        }
    }

}


2.替换类型中的泛型

var listType = typeof(List<>);
var listofType = listType.MakeGenericType(new[] { Type.GetType("UnitTest.C") });
dynamic list = Activator.CreateInstance(listofType);
list.Add(new C() { i1=1 });
list.Add(new C() { i1 = 2 });
var list1 = list;

0 0