我有一个dll,我想在运行时加载它。我使用加载程序集的Assembly.Load(byte[])和.CreateInstance()。
在这个程序集中,我有一个接口IAnimal和一个实现这个接口的牛:
namespace DynamicLoading
{
public class Cow : IAnimal
{
public string GetName()
{
return "This is cow";
}
}
public interface IAnimal
{
string GetName();
}
}我使用一个控制台应用程序来测试加载如下:
namespace DynamicLoading
{
class Program
{
static void Main(string[] args)
{
byte[] assemblyStream = System.IO.File.ReadAllBytes(@"C:\Cow\Cow.dll");
var cow = Assembly.Load(assemblyStream);
//Returns null: it is not able to cast from Cow to IAnimal
var newCow = cow.CreateInstance("DynamicLoading.Cow", false) as IAnimal;
Console.WriteLine(newCow.GetName());
Console.ReadLine();
}
}
public interface IAnimal
{
string GetName();
}
}我可以很好地实例化一个新的Cow实例,但是我似乎不能强制执行IAnimal接口(我在测试项目和dll项目中都创建了这个接口)。dll中的牛不希望从testclass.中被抛到IAnimal中。
如何在奶牛上调用方法,如GetName()?
干杯伙计们!
发布于 2013-12-24 16:06:21
Cow.dll中的接口与其他程序集中的接口不一样。,不管是,如果它是同一个名称空间中具有相同名称的接口。
您需要做的是在一个“公共”位置定义接口,Cow.dll和您的程序集都可以看到:
- Animals.Common.Dll
- interface IAnimal
- Animals.Cow.Dll
- References
- Animals.Common.Dll
- class Cow: IAnimal
- Animals.Main.exe (Console Application)
- References
- Animals.Common.Dll
- class Program发布于 2013-12-24 16:05:49
您有两个不同的接口,尽管它们具有相同的FullName,但它们的AssemblyQualifiedName不同,因为它们属于两个不同的程序集。
在由两个项目引用的某些共享程序集中使用IAnimal接口的单个定义。
如果您希望定期执行这类操作(类型的动态加载),请查看MAF,它是为创建加载项而设计的。
发布于 2013-12-24 16:05:06
不要在多个地方定义接口,在DynamicLoading库中实现的版本与类库中的版本不一样。
在第三个程序集中创建一个版本,并从控制台和DynamicLoading程序集引用该版本。
例如。
汇编DynamicLoading.Core IAnimal
程序集DynamicLoading.Cow -参考DynamicLoading.Core
Consoe应用-参考DynamicLoading.Core
https://stackoverflow.com/questions/20763613
复制相似问题