Aam*_*mir 3 c# reflection c#-4.0
请考虑DLL中的以下代码:
public class ReceivingClass
{
private Assembly myAssembly;
private Type typeOfClass;
public ReceivingClass()
{
myAssembly = Assembly.LoadFile(@"E:\VSProjects\TestDynamicLinking\MyLib\bin\Debug\MyLib.dll");
//Can I use this type somehow to resolve the type in the below method?
typeOfClass = myAssembly.GetType("ExportedClass");
}
public bool ReceiveMethod(ExportedClass classobj)
{
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
所以,问题是在ReceiveMethod上面,ExportedClass是一个在Assembly中定义的类,我在构造函数中动态加载.那么,我可以以某种方式解决ExportedClass我不必使用的类型dynamic吗?
你有一些选择
我通常会使用第二种方法.只需定义ExportedClass在另一个(共享)程序集中实现的接口.然后,您可以尝试将创建的实例强制转换为该接口.像那样:
ISomeInterface obj = Activator.CreateInstance(typeOfClass) as ISomeInterface;
Run Code Online (Sandbox Code Playgroud)
当然,这是假设您可以控制引用的库.或者,如果您要定义插件基础结构或类似内容,则应将其作为一项要求包含在内.
| 归档时间: |
|
| 查看次数: |
902 次 |
| 最近记录: |