垂头丧气无法正常工作.我做错了吗? [英] Downcast not working. Am I doing it wrong?

查看:114
本文介绍了垂头丧气无法正常工作.我做错了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从程序集中加载类并尝试实例化和实例.

这就是我所拥有的

I am loading a class from an assembly and trying to instantiate and instance.

Here''s what I have

public interface IActivity


public abstract class BaseActivity:IActivity


public class MyActivity:BaseActivity //I don't really call stuff MyXxx


并加载它:


And to load it:

Type type = validIActivityTypes.Single(); //I've already performed my checks for this
ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
if (constructor == null)
   return result;
IActivity activity = (IActivity)constructor.Invoke(null);



此时,类型"是"MyActivity",但是...

动臂:



At this point, the ''type'' is ''MyActivity'' but...

Boom:

报价:

ServerControls.dll中发生类型为"System.InvalidCastException"的第一次机会异常.

附加信息:无法将类型为"WorkFlowEngine.Activities.MyActivity"的对象转换为类型为"WorkFlowEngine.Interfaces.IActivity".

A first chance exception of type ''System.InvalidCastException'' occurred in ServerControls.dll

Additional information: Unable to cast object of type ''WorkFlowEngine.Activities.MyActivity'' to type ''WorkFlowEngine.Interfaces.IActivity''.



我做错了什么?

谢谢

刚刚测试type.GetInterfaces():



What am I doing wrong?

Thanks

Just tested type.GetInterfaces():


> type.GetInterfaces()| {System.Type [1]}
> [0] | {Name ="IActivity" FullName ="WorkFlowEngine.Interfaces.IActivity"}

>type.GetInterfaces() | {System.Type[1]}
>[0] | {Name = "IActivity" FullName = "WorkFlowEngine.Interfaces.IActivity"}

推荐答案

好-我做错了:

我的活动类型与IActivity接口位于同一程序集中.

加载程序集时,所有相关程序集也将加载到AppDomain中,除非已将其加载到AppDomain中.

如果通过反射加载装配件,则它将仍然被加载,并且将与引用的装配件不同.

所以本质上我确实加载了两个版本的IActivity :(


解决方案很简单.我已将接口声明移至差异程序集(项目)中,该程序集同时由应用程序和加载的dll引用.这意味着加载的dll将使用预加载的接口程序集而不是其自己的副本.

这样就解决了这个问题(由Richard Deeming在1秒前突出显示)

谢谢大家的关注,^ _ ^
Ok - i was doing it wrong:

My activity type lived in the same assembly as the IActivity interface.

When you load an assembly, all related assemblies will also be loaded into the AppDomain unless it has already been loaded into the AppDomain .

If you load an assembly through reflection then it will still be loaded and will not be the same as the referenced assembly.

So essentially I did have two versions of the IActivity loaded :(


The solution is simple. I have moved my interface declarations into a difference assembly (project) which is referenced by both the app and the loaded dll. This means that the loaded dll will use the pre-loaded interface assembly instead of it''s own copy.

Thus the issue (highlighted by Richard Deeming at 1 sec ago) is solved

Thanks for looking into this, guys ^_^


这篇关于垂头丧气无法正常工作.我做错了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆