2012-10-07 25 views
0

我试图使用预编译的DLL与反思,以实例为我的类的接口是在DLL反射麻烦。我尝试了这本书,但它不会工作。它引发InvalidCastException当我尝试做一些事情,如:InvalidCastException的,DLL和C#中

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... 



     } 
    } 
} 

谁能帮助我?谢谢!

+2

是'ICompute'声明两次?每次组装一次?如果是这样,那是你的问题。仅仅因为两个接口具有相同的成员不会使它们成为相同的接口。 – vcsjones

+0

你有没有尝试使用.NET 4和动态?如果iCompute是动态的,那么它可能工作。 –

+0

@vcsjones 起初我还以为同一然后重新编译我的DLL以这样的方式 CSC /目标:库/reference:Program.exe /out:mylib.dll ClassThatImplementsICompute.cs 我做了它可能是错的方式第一次: CSC /目标:库/out:mylib.dll Program.cs的ClassThatImplementsICompute.cs – TechInstinct

回答

1

的问题是你如何与Assembly.LoadFrom()加载程序集做。

LoadFrom()负荷组装成不同的上下文相比ICompute接口您要投给的情境。如果可能,尽量使用Assembly.Load()。即将组件放入垃圾箱/探测路径文件夹并以完整强名称加载。

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

+0

尝试。不起作用。也许我以错误的方式编译我的DLL? – TechInstinct

+0

具有ICompute接口的程序集是否已签名?为了正确投射。 ICompute接口需要来自同一个程序集,相同的物理文件具有相同的强名称。我没有尝试类似没有强名称的东西,所以我不确定未签名程序集的行为。 – airmanx86

+0

呃,其实我不知道我是否明白你在问什么。对不起,我对C#比较陌生。我创建了2个文件,其中的内容完全相同我的ICompute接口定义在Program.cs文件中,ClassThatImplementsICompute.cs文件中的ClassThatImplementsICompute。我使用命令行csc Program.cs编译,然后使用ClassThatImplementsICompute.cs引用Program.exe来定义接口。精确的命令:** csc/target:library /reference:Program.exe /out:mylib.dll ClassThatImplementsICompute.cs **。有效。然后,我只是将mylib.dll移到了VS的Debug中,然后运行它。 – TechInstinct