![](/img/trans.png)
[英]Unable to Create the instance of COM class using Activator.CreateInstance
[英]Using Activator.CreateInstance to create instance of a class and inject Interface to constructor
我的目標是從它的AssemblyQualifiedName創建一個類的實例。 問題是這個類需要在它的構造函數中傳遞一個接口,而我在使用Activator.CreateInstance時遇到這個問題。
先謝謝您的幫助。
一旦我有了要實例化的類的AssemblyQualifiedName,我就使用Type.GetType(AQN)獲取它的類型,使用該類型查找構造函數並獲取所需的參數。
我在調用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);
}
一旦我這樣做,我得到錯誤“找不到類型xxx上的構造函數。”
有一個Activator.CreateInstance ,只需要傳遞類型和參數。 所以你可以說:
ISomeInterface something = null;
var objectType = Type.GetType(AQN);
var instance = Activator.CreateInstance(objectType, something);
如果你想動態創建一個類的實例,那么你也可以這樣做
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.