我在使用反射实例化DLL文件中定义的类时遇到了一些问题。尽管代码看起来很好,但我在Activator.CreateInstance上得到了Activator.CreateInstance。代码如下(目前只有一个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
任何帮助都是非常感谢的!提前谢谢你。
发布于 2014-04-20 22:09:59
您必须将所有依赖项复制到文件夹扩展中。在您的示例中,您缺少了SortingFunctions.dll ( BubbleSort.dll所依赖的)。它反映在内部异常中。
https://stackoverflow.com/questions/23187926
复制相似问题