【问题标题】:Cast class to base interface via reflection cause exception通过反射将类转换为基接口导致异常
【发布时间】:2012-01-18 21:03:59
【问题描述】:

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

MyDLL.dll

public interface MyInterface
{
    void MyMethod();
}

MyOtherDLL.dll

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();
    }
}

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

【问题讨论】:

    标签: class c#-4.0 reflection interface casting


    【解决方案1】:

    您正在尝试将Type 类型的.NET 框架对象强制转换为您创建的接口。 Type 对象没有实现你的接口,所以它不能被强制转换。您应该首先创建对象的特定实例,例如通过使用 Activator 像这样:

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

    CreateInstance 方法还有其他可能满足您需求的重载。

    【讨论】:

    • 你是对的。我忘了创建该类型的实例。谢谢!
    猜你喜欢
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多