![](/img/trans.png)
[英]Why can't Activator.CreateInstance<>() find an internal parameterless constructor?
[英]Why cant Activator.CreateInstance find the constructor?
我在運行時加載DLL。 DLL和主應用程序都使用DLL保存接口,讓程序知道如何使用DLL中的某些類型。 在主應用程序中有一個Factory類,當主應用程序請求它繼承的接口時,Dll可以設置其中一個對象類型。 下面是從DLL創建對象類型的函數的條帶化(主要是刪除的錯誤處理代碼)版本。 當這個被調用時,我得到一個異常,說沒有為這個對象定義無參數構造函數。 我不知道為什么,因為他們都有無參數構造函數。
//inside the DLL
Factory.ResovleType<ISomething>(typeof(SomethingCool));
//inside the main application
ISomething obj = Factory.CreateObject<ISomething>();
//inside the Factory Class
public static T CreateObject<T>(params object[] args)
{
T obj = (T)Activator.CreateInstance(resovledList[typeof(T)], args);
return obj;
}
public static void ResolveType<T>(Type type)
{
resovledList.Add(typeof(T), type);
來自評論:
resovledList[typeof(T)]
找到的類型不是預期的類型。 相反,它是RuntimeType
。 這可能是調用ResolveType<ISomething>(typeof(Something).GetType())
而不是ResolveType<ISomething>(typeof(Something))
:
typeof(Something)
是Type
的值(實際上是RuntimeType
,它派生自Type
),因此調用typeof(Something).GetType()
會為您提供typeof(RuntimeType)
。
事實證明,你實際上是在其他地方調用GetType()
,但問題和解決方案是相同的:你不應該在這里調用GetType()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.