C#将类强制转换为接口列表

C#将类强制转换为接口列表,c#,interface,casting,invoke,C#,Interface,Casting,Invoke,我正在尝试动态加载一些.dll文件。这些文件是插件(目前为自编),至少有一个类实现了MyInterface。对于每个文件,我将执行以下操作: Dictionary<MyInterface, bool> _myList; // ...code Assembly assembly = Assembly.LoadFrom(currentFile.FullName); foreach (Type type in assembly.GetTypes())

我正在尝试动态加载一些.dll文件。这些文件是插件(目前为自编),至少有一个类实现了
MyInterface
。对于每个文件,我将执行以下操作:

    Dictionary<MyInterface, bool> _myList;

    // ...code

    Assembly assembly = Assembly.LoadFrom(currentFile.FullName);
    foreach (Type type in assembly.GetTypes())
    {
        var myI = type.GetInterface("MyInterface");
        if(myI != null)
        {
            if ((myI.Name == "MyInterface") && !type.IsAbstract)
            {
                var p = Activator.CreateInstance(type);
                _myList.Add((MyInterface)p, true);
            }
        }
    }
这段代码是第一次尝试加载插件,我还不知道为什么
p
null

我希望有人能引导我找到正确的方法:)

有一种更简单的方法来检查您的类型是否可以转换到您的界面

Assembly assembly = Assembly.LoadFrom(currentFile.FullName);
foreach (Type type in assembly.GetTypes())
{
    if(!typeof(MyInterface).IsAssignableFrom(type))
        continue;

    var p = Activator.CreateInstance(type);
    _myList.Add((MyInterface)p, true);
}

如果
IsAssignableFrom
为false,则说明您的继承有问题,这很可能是导致错误的原因。

请查看以下代码。我想在这种情况下我能帮你

Assembly assembly = Assembly.LoadFrom(currentFile.FullName);
///Get all the types defined in selected  file
Type[] types = assembly.GetTypes();

///check if we have a compatible type defined in chosen  file?
Type compatibleType = types.SingleOrDefault(x => typeof(MyInterface).IsAssignableFrom(x));

if (compatibleType != null)
{
    ///if the compatible type exists then we can proceed and create an instance of a platform
    found = true;
    //create an instance here
    MyInterface obj = (ALPlatform)AreateInstance(compatibleType);

}

您应该认真阅读Jon Skeet的文章,其中解释了您看到的行为以及如何正确地执行插件框架。

这段代码不起作用,什么是x以及在哪里初始化它?在上面的代码片段中,“if(x!=null)”中的“x”真的应该是“myI”吗?您还应该验证该类型是否具有默认构造函数,因为您的代码假设。我不理解
var myI=type.GetInterface(“MyInterface”);如果(x!=null)
。如果(myI!=null),它应该是
?假设存在您的类型的无参数构造函数。你会得到什么样的例外?如果它是
MissingMethodException
,那么问题(几乎可以肯定)是您的类没有无参数构造函数。是的,它是
false
。但是我现在只有一个成员,真的不知道继承会有什么问题。你的“插件”程序集引用了定义接口的程序集吗?你运行的代码(示例中的代码)引用了相同的程序集吗?我能从中得到的是插件的程序集与我的应用程序的程序集不一样。我希望更多的人支持这个程序集,因为我认为这可能是OP的问题。基本上,如果你认为这是C++,以及接口定义,比如.h文件,你会遇到这个错误。如果您以“托管类型”的方式考虑它,您将看到有两个接口,每个文件一个,如果它按照链接所说的(错误的)方式编译。
Assembly assembly = Assembly.LoadFrom(currentFile.FullName);
///Get all the types defined in selected  file
Type[] types = assembly.GetTypes();

///check if we have a compatible type defined in chosen  file?
Type compatibleType = types.SingleOrDefault(x => typeof(MyInterface).IsAssignableFrom(x));

if (compatibleType != null)
{
    ///if the compatible type exists then we can proceed and create an instance of a platform
    found = true;
    //create an instance here
    MyInterface obj = (ALPlatform)AreateInstance(compatibleType);

}