0

我正在尝试使用带有反射的预编译 DLL,为我的类在 DLL 中实例化一个接口。我按书本试过,但它不起作用。当我尝试执行以下操作时,它会抛出 InvalidCastException:

ICompute iCompute = (ICompute)Activator.CreateInstance(type);

当然类型是我的实现 ICompute 接口的类。我被困住了,不知道该怎么办。完整代码如下:

这是 DLL 内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication18
{
    public class ClassThatImplementsICompute : ICompute
    {
       public int sumInts(int term1, int term2)
       {
           return term1 + term2;
       }

       public int diffInts(int term1, int term2)
       {
           return term1 - term2;
       }
    }
}

实际程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Reflection;

namespace ConsoleApplication18
{

    public interface ICompute
    {
        int sumInts(int term1, int term2);
        int diffInts(int term1, int term2);
    }



    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Loading dll...");
            Assembly assembly = Assembly.LoadFrom("mylib.dll");

            Console.WriteLine("Getting type...");
            Type type = assembly.GetType("ConsoleApplication18.ClassThatImplementsICompute");
            if (type == null) Console.WriteLine("Could not find class type");

            Console.WriteLine("Instantiating with activator...");
            //my problem!!!
            ICompute iCompute = (ICompute)Activator.CreateInstance(type);

            //code that uses those functions...



        }
    }
}

谁能帮我?谢谢!

4

1 回答 1

1

问题与您如何加载程序集有关Assembly.LoadFrom()

LoadFrom()ICompute与您尝试转换到的接口的上下文相比,将程序集加载到不同的上下文中。Assembly.Load()如果可能,请尝试使用。即将程序集放入 bin / probing path 文件夹并按完整的强名称加载。

一些参考资料: http: //msdn.microsoft.com/en-us/library/dd153782.aspx http://blogs.msdn.com/b/suzcook/archive/2003/05/29/57143.aspx(见LoadFrom 的劣势位)

于 2012-10-07T00:31:07.187 回答