[英]Using Activator.CreateInstance to create instance of a class and inject Interface to constructor
My goal is to create an instance of a class from it's AssemblyQualifiedName. 我的目标是从它的AssemblyQualifiedName创建一个类的实例。 The problem is that this class requires an interface to be passed in it's constructor and I am having trouble doing this with Activator.CreateInstance.
问题是这个类需要在它的构造函数中传递一个接口,而我在使用Activator.CreateInstance时遇到这个问题。
Thanks in advance for the help. 先谢谢您的帮助。
Once i have the AssemblyQualifiedName of the class I want to instantiate I got it's type using Type.GetType(AQN), used that type to find the constructor and get the required parameters. 一旦我有了要实例化的类的AssemblyQualifiedName,我就使用Type.GetType(AQN)获取它的类型,使用该类型查找构造函数并获取所需的参数。
I get stuck when calling Activator.CreateInstance and passing the parameters. 我在调用Activator.CreateInstance并传递参数时遇到困难。
var objectType = Type.GetType(AQN);
var constructors = objectType.GetConstructors();
foreach (ConstructorInfo constructor in constructors)
{
var parameters = constructor.GetParameters();
var instantiatedObj = Activator.CreateInstance(objectType,parameters);
}
Once I do this i get the error "Constructor on Type xxx not found." 一旦我这样做,我得到错误“找不到类型xxx上的构造函数。”
There's a Activator.CreateInstance that simply takes the type and the parameters to pass. 有一个Activator.CreateInstance ,只需要传递类型和参数。 So you can just say:
所以你可以说:
ISomeInterface something = null;
var objectType = Type.GetType(AQN);
var instance = Activator.CreateInstance(objectType, something);
if you want to create an instance of the class dynamically then you can do it like this too 如果你想动态创建一个类的实例,那么你也可以这样做
Type type = Type.GetType(AQN);
PropertyInfo[] properties = type.GetProperties();
var instance = (BaseClass)Activator.CreateInstance(type);
for (int i = 0; i < properties.Length; i++)
{
PropertyInfo propertyInfo = type.GetProperty(properties[i].Name);
var propertyVal = Convert.ChangeType(yourpropertyvalue,
properties[i].PropertyType);
propertyInfo.SetValue(instance, propertyVal);
}
return instance;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.