【发布时间】:2014-04-20 21:45:37
【问题描述】:
我在使用反射实例化 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
任何帮助将不胜感激!提前谢谢你。
【问题讨论】:
-
那么,异常包含哪些信息?它可能会告诉你一些事情。全部分析。
-
我遇到了同样的问题,在查看了内部异常之后,我发现我试图将一个对象添加到一个空列表。
标签: c# activator createinstance targetinvocationexception