Class 通过反射将类强制转换为基接口导致异常

Class 通过反射将类强制转换为基接口导致异常,class,c#-4.0,reflection,interface,casting,Class,C# 4.0,Reflection,Interface,Casting,我通过反射以友好的方式加载.NET程序集,并获取它包含的所有类(目前是一个)。在此之后,我尝试将该类强制转换为一个接口,我100%确定该类实现了该接口,但我收到了以下异常:无法将System.RuntimeType类型的对象强制转换为MyInterface类型 MyDLL.dll public interface MyInterface { void MyMethod(); } public class MyClass : MyInterface { public void M

我通过反射以友好的方式加载.NET程序集,并获取它包含的所有类(目前是一个)。在此之后,我尝试将该类强制转换为一个接口,我100%确定该类实现了该接口,但我收到了以下异常:无法将System.RuntimeType类型的对象强制转换为MyInterface类型

MyDLL.dll

public interface MyInterface
{
    void MyMethod();
}
public class MyClass : MyInterface
{
    public void MyMethod()
    {
        ...
    }
}

public class MyLoader
{
    Assembly myAssembly = Assembly.LoadFile("MyDLL.dll");
    IEnumerable<Type> types = extension.GetTypes().Where(x => x.IsClass);

    foreach (Type type in types)
    {
        ((MyInterface)type).MyMethod();
    }
}
MyOtherDLL.dll

public interface MyInterface
{
    void MyMethod();
}
public class MyClass : MyInterface
{
    public void MyMethod()
    {
        ...
    }
}

public class MyLoader
{
    Assembly myAssembly = Assembly.LoadFile("MyDLL.dll");
    IEnumerable<Type> types = extension.GetTypes().Where(x => x.IsClass);

    foreach (Type type in types)
    {
        ((MyInterface)type).MyMethod();
    }
}
公共类MyClass:MyInterface
{
公共方法()
{
...
}
}
公共类装载机
{
Assembly myAssembly=Assembly.LoadFile(“MyDLL.dll”);
IEnumerable types=extension.GetTypes()。其中(x=>x.IsClass);
foreach(类型中的类型)
{
((MyInterface)类型).MyMethod();
}
}

我已经删除了所有不必要的代码。我基本上就是这么做的。我看到Andi回答的问题与我的问题似乎相同,但我无法解决它。

您正在尝试将类型为
的.NET framework对象强制转换为您创建的接口。
类型
对象未实现您的接口,因此无法强制转换。您应该首先创建对象的特定实例,例如使用
Activator
,如下所示:

// this goes inside your for loop
MyInterface myInterface = (MyInterface)Activator.CreateInstance(type, false);
myInterface.MyMethod();

CreateInstance
方法具有其他重载,这些重载可能适合您的需要。

您是对的。我忘了创建该类型的实例。非常感谢。