[英]TargetInvocationException on Activator.CreateInstance
我在使用Reflection實例化DLL文件中定義的類時遇到了一些麻煩。 即使代碼看起來很好,我在Activator.CreateInstance上得到了TargetInvocationException。 代碼如下(現在只有一個DLL可用):
public Comparator()
{
string[] filePaths = Directory.GetFiles(@".\Extensions");
for (int i = 0; i < filePaths.Length; ++i)
{
var asm = Assembly.LoadFrom(Path.GetFullPath(filePaths[i]));
if (asm != null)
{
foreach (Type currType in asm.ExportedTypes)
{
if (!currType.IsAbstract && currType.IsPublic && typeof(SorterBase).IsAssignableFrom(currType))
{
Debug.WriteLine(currType); //outputs: BubbleSort.Sorter
var instance = Activator.CreateInstance(currType); //TargetInvocationException
}
}
}
}
}
這是我試圖實例化的類:
using SortingLibrary;
using SortingFunctions;
namespace BubbleSort
{
public class Sorter : SorterBase //SorterBase is an abstract class defined in SortingLibrary
{
public Sorter()
{
SetFunction(Sorting.BubbleSort);
AlgorithmName = @"Bubble Sort";
}
}
}
我設法防止該問題發生的唯一方法是在編譯之前將加載的.dll添加到引用。 問題是,通常在編譯期間無法確定需要加載哪些庫。 我在這里錯過了什么?
整個解決方案(雖然目前有點亂)可以在這里下載: http : //nazr.in/rOD
任何幫助將非常感謝! 先感謝您。
您必須將所有依賴項復制到Extensions文件夾。 在您的情況下,您缺少BubbleSort.dll依賴的SortingFunctions.dll。 它反映在內部異常中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.