Bootstrap

C# - 反射创建泛型类实例 和 反射给List<T>添加元素


namespace xxx
    public class A<T> 
    {
        public List<T> Datas;
    }
}
namespace xxx
{
    public struct Data{}
}

var dataTTypeName = "xxx.Data";  
var dataTType = Assembly.Load("xxx").GetType(dataTTypeName);  //具体的泛型类型

Type instClass = typeof(xxx.A<>);        //获取到泛型类的类型
Type constructedClass = dataClass.MakeGenericType(dataTType);   //通过反射,创建泛型类的目标类型,参数为泛型的目标类型
var instObject = Activator.CreateInstance(constructedClass);
//反射创建一个List<>类型实例
var listClass = typeof(List<>);
var listConstructedClass = listClass.MakeGenericType(dataTType);
var fieldList = constructedClass.GetField("Datas").GetValue(configDataObject);
fieldList ??= Activator.CreateInstance(listConstructedClass);

var elementData = Activator.CreateInstance(dataTType);

//反射List<T>调用Add方法
var addMethodInfo = listConstructedClass.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public);
addMethodInfo.Invoke(fieldList, new object[] { elementData });

//反射赋值实例的字段,将"List<>"类型实例赋值给"ExcelConfigData<T>类型实例"的“Datas”字段
constructedClass.GetField("Datas").SetValue(instObject, fieldList);

;