Ana*_*nya 9 .net reflection instance generic-type-argument
嗨,我需要在运行时使用反射为列表对象创建实例.例如,我有2个类,如下所示,
class Class1
{
List<Class2> class2List;
public List<Class2> Class2List
{
get;set;
}
}
class Class2
{
public string mem1;
public string mem2;
}
Run Code Online (Sandbox Code Playgroud)
Class1在另一个类中创建Runtime 实例后Class3,我想为该类的所有属性赋值.在这种情况下,Class2List是属性List<Class2>.在运行时,我不知道类的类型List<Class2>.如何List<Class2>在运行时初始化属性,即在class3内部.
任何建议都非常感谢...
And*_*tan 19
而不是质疑你的动机或试图解开你正在做的事情 - 我只是回答标题中的问题.
假设您有一个类型实例listElemType,它表示List<>在运行时传递给该类型的类型参数:
var listInstance = (IList)typeof(List<>)
.MakeGenericType(listElemType)
.GetConstructor(Type.EmptyTypes)
.Invoke(null);
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过它的IList接口实现来处理列表.
或者,实际上,您可以停止MakeGenericType呼叫并使用它在呼叫中生成的类型Activator.CreateInstance- 如Daniel Hilgarth的回答.
然后,给定一个target要设置其属性的对象:
object target; //the object whose property you want to set
target.GetType()
.GetProperty("name_of_property") //- Assuming property is public
.SetValue(target, listInstance, null); //- Assuming .CanWrite == true
// on PropertyInfo
Run Code Online (Sandbox Code Playgroud)
如果您不知道所代表的类型的属性target,那么您需要使用
target.GetType().GetProperties();
Run Code Online (Sandbox Code Playgroud)
获取该实例的所有公共属性.然而,只是能够创建一个列表实例并不能真正帮助你 - 你必须有一个更通用的解决方案,可以应付任何类型.除非你打算专门针对列表类型.
听起来像你可能需要一个共同的界面或基础......