繁体   English   中英

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

[英]C# cast a class to an Interface List

我正在尝试动态加载一些.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);
            }
        }
    }

运行此操作会导致强制转换异常,但我找不到解决方法。 无论如何,我想知道为什么这根本不起作用。 我正在寻找.NET Framework 3.5中的解决方案。

发生在我身上的另一件事是在上面的代码中向_myList添加新条目之前运行以下内容后在p中获取null

var p = type.InvokeMember(null, BindingFlags.CreateInstance, null,
                          null, null) as MyInterface;

这段代码是第一次加载插件的尝试,我没有找到为什么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,则继承有问题,这很可能是导致错误的原因。

您应该真正阅读插件并通过Jon Skeet强制转换异常 ,它解释了您看到的行为以及如何正确地执行插件框架。

请查看以下代码。 我认为Type.IsAssignableFrom(Type type)可以帮助你解决这种情况。

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM