我正在尝试在运行时从dll动态加载一个类,然后将其转换为接口。
我在一个名为MyClass.dll的dll中有一个类定义,如下所示。
namespace MyClass
{
public class Class1 : IMyInterface
{
public int MyNumber { get; set; } = 6;
public int GetMyNumber()
{
return MyNumber;
}
}
}
然后,我在共享dll中定义了一个接口,如下所示:
namespace Common
{
public interface IMyInterface
{
int MyNumber { get; set; }
int GetMyNumber();
}
}
最后,我尝试加载程序集并将其指定为IMyInterface。
private void Form1_Load(object sender, EventArgs e)
{
string fName = @"D:\Development\Research\Dynamic Load\MyClass\bin\Debug\MyClass.dll";
Assembly decoupledAssembly = Assembly.LoadFrom(fName);
if (decoupledAssembly != null) //All Good
{
Type t = decoupledAssembly.GetType("MyClass.Class1");
//Good here too, it finds it just fine.
IMyInterface mi = (Activator.CreateInstance(t) as IMyInterface);
//Now i'm screwed screwed.
if (mi != null)
MessageBox.Show(mi.GetMyNumber().ToString());
}
}
您可以在评论中看到它正在破碎。我找到了类型,没有问题,但当我尝试将其作为我的界面时,它返回null。
提前感谢您的帮助。
答案 0 :(得分:0)
您必须引用该接口的完整路径。很奇怪,但是一旦我这样做了它就开始工作了。请参阅以下更改。
namespace MyClass
{
public class Class1 : Common.IMyInterface
{
public int MyNumber { get; set; } = 6;
public int GetMyNumber()
{
return MyNumber;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
string fName = @".....\MyClass.dll";
Assembly decoupledAssembly = Assembly.LoadFrom(fName);
if (decoupledAssembly != null) //All Good
{
Type t = decoupledAssembly.GetType("MyClass.Class1");
//Good here too, it finds it just fine.
Common.IMyInterface mi = (Activator.CreateInstance(t) as Common.IMyInterface);
//Now it works.
if (mi != null)
MessageBox.Show(mi.GetMyNumber().ToString());
}
}