小编MaT*_*aTi的帖子

Activator.CreateInstance 上的 TargetInvocationException

我在使用反射实例化 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
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我试图实例化的类:

using SortingLibrary;
using SortingFunctions;
namespace BubbleSort
{
    public class Sorter : SorterBase //SorterBase is an abstract class defined in …
Run Code Online (Sandbox Code Playgroud)

c# createinstance activator targetinvocationexception

3
推荐指数
1
解决办法
2854
查看次数