InvalidCastException when creating an instance usi

2019-08-21 09:14发布

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;

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

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.

标签: c# reflection
2条回答
混吃等死
2楼-- · 2019-08-21 09:54

The InvalidCastException should contain more details, like 'cannot cast x to y'.
My guess is that the assembly containing IInterface that you are loading is not exactly the same as the one your code was built against, maybe it's a local copy of a non strongly-named assembly.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-08-21 10:19

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.

查看更多
登录 后发表回答