C# C语言中的InvalidCastException、DLL和反射故障#
我试图使用一个带有反射的预编译DLL,为DLL中的类实例化一个接口。我试着照本宣科,但行不通。当我尝试执行以下操作时,它会引发InvalidCastException:C# C语言中的InvalidCastException、DLL和反射故障#,c#,reflection,dll,interface,.net,C#,Reflection,Dll,Interface,.net,我试图使用一个带有反射的预编译DLL,为DLL中的类实例化一个接口。我试着照本宣科,但行不通。当我尝试执行以下操作时,它会引发InvalidCastException: ICompute iCompute = (ICompute)Activator.CreateInstance(type); 其中类型当然是实现ICompute接口的类。我被卡住了,不知道该怎么办。完整代码如下: 这是DLL内容: using System; using System.Collections.Generic; u
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...
}
}
}
有人能帮我吗?谢谢 问题在于如何使用
assembly.LoadFrom()
加载程序集
LoadFrom()
将程序集加载到与您试图强制转换到的i计算机接口的上下文不同的上下文中。如果可能,尝试使用Assembly.Load()
。i、 e.将程序集放入bin/probling path文件夹,并按完整的强名称加载
一些参考资料:
(参见LoadFrom的缺点位)是否两次声明了ICompute
?每次装配一次?如果是这样,那就是你的问题。仅仅因为两个接口具有相同的成员并不能使它们成为相同的接口。您是否尝试使用.NET 4和dynamic?如果iComputer是动态的,那么它可能会起作用。@vcsjones起初我也这么想,然后用以下方式重新编译了我的dll:csc/target:library/reference:Program.exe/out:mylib.dll类实现了compute.cs第一次这样做可能是错误的:csc/target:library/out:mylib.dll Program.cs类实现了compute.csi是拥有ICompute.cs的程序集接口签名?让它正确地投射。iComputer接口需要来自相同的程序集、相同的物理文件、相同的位置和相同的强名称。我没有尝试过没有强名称的类似操作,因此我不确定未签名程序集的行为。实际上,我不知道我是否理解您的要求。对不起,我对C#比较陌生。我创建了两个文件,上面的内容完全相同。我的ICompute接口定义在Program.cs文件中,实现Compute的类在实现Compute.cs文件的类中。我使用命令行csc Program.cs编译,然后使用引用Program.exe进行接口定义的类来实现compute.cs。确切的命令:csc/target:library/reference:Program.exe/out:mylib.dll实现compute.cs的类。成功了。然后我将mylib.dll移动到VS中调试并运行它。我可能不知道如何进行调试,而且对此我没有很好的参考资料,所以我唯一的希望是询问真正的编码人员,他们都知道。你确定csproj文件实际上没有对Program.exe进行签名(这使它成为一个与只执行CSC Program.cs不同的程序集)。我只使用CSC进行了几次测试,您的代码可以正常工作(在.NET4.5中)。事实上,您是对的,这很奇怪。我按照你说的重新编译了它,它很有效。现在,我想知道发生了什么,为什么。我仍然不知道签名是什么意思,但我会搜索它。