使用 assembly.CreateInstance 创建实例时出现 InvalidCastException [英] InvalidCastException when creating an instance using assembly.CreateInstance

查看:38
本文介绍了使用 assembly.CreateInstance 创建实例时出现 InvalidCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找对以下内容的解释 -我有一个正在使用的程序集

I'm looking for an explanation for the following - I have an assembly I'm loading using

Assembly assembly = Assembly.LoadFrom(filename);

然后我在程序集中的所有类型上循环,并希望尝试找出一个类型是否实现了一个特定的接口,如果是,我想要一个该类型的实例,我已经尝试了一些不起作用的东西,但是当我回到最基本的(可能是低效的)方式时,我意识到有一些更基本的东西我不明白 -

I then loop on all the types in the assembly, and wish to try and find out if a type implements a particular interface and if so I want an instance of that type, I've tried several things which did not work, but when I fell back to the most basic (and probably inefficient) way, I realised there's something more fundamental I don't understand -

            foreach (Type t in assembly.GetTypes())
            {
                foreach (Type i in t.GetInterfaces())
                {
                    if (i.FullName == pluginInterfaceType.FullName)
                    {
                        object o = assembly.CreateInstance(t.ToString());
                        IInterface plugin = (IInterface)o;

最后一行导致 InvalidCastException,尽管创建的类型确实实现了该接口.

That last line causes an InvalidCastException, despite the fact that the type created definitely implements that interface.

更多 - 如果我使用 Activator.CreateInstance 而不是 Assembly.CreateInstance(我不想这样做),转换到界面工作得很好.

Further more - if I use Activator.CreateInstance instead of Assembly.CreateInstance (which I don't want to do), casting to the interface works just fine.

推荐答案

这很可能是因为您要转换到的界面与您在类中找到的界面不同.

This is most probably because the interface you are casting to is not the same you find in the class.

要么是因为有更多同名的接口,要么是因为你加载了不止一次.例如,因为它是在程序集中定义的,所以您是动态加载的,并且您尝试将其强制转换为静态绑定的.

Either because there is more the one interface with the same name, or because you loaded it more then once. For instance, because it is defined in the assembly you are dynamically loaded, and you try to cast it to the one that is statically bound.

这篇关于使用 assembly.CreateInstance 创建实例时出现 InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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