繁体   English   中英

Assembly.CreateInstance类型转换返回null

[英]Assembly.CreateInstance type conversion returns null

我正在尝试在运行时加载和使用DLL,这工作正常:

var pluggin = asm2.CreateInstance("ParserTest.Interface", true) as iPluggin;

但这不是(我需要遍历特定文件夹中的DLL文件以找到实现iPluggin接口的正确文件):

...
var asm = Assembly.LoadFrom(dll.FullName);
if (asm.GetExportedTypes().FirstOrDefault(q => q.GetInterface(tName) != null) == null) continue;
Project.ProcessList.Add(asm.CreateInstance(tName, true) as iPluggin);
...

在调试模式下进行了一些研究,我发现:

asm.CreateInstance(tName, true)

返回正确的对象,但是当尝试将其强制转换为iPluggin时,结果为null。 知道为什么吗?

我做了类似的事情:

private readonly Type _pluginbaseType = typeof(BasePlugin);

public AssemblyPlugin(Assembly assembly)
{

    Type[] _plugins = _assembly.GetExportedTypes()
        .Where(t => t.BaseType.IsSubclassOf(_pluginbaseType)
        .ToArray();
}

之后,您可以:

BasePlugin plugin = (BasePlugin)Activator.CreateInstance(pluginType);

您应该更喜欢基类而不是接口。

先生解决了,尽管我不明白。

定义了de interface(SDK.dll)的DLL已在检查之中。 我现在按预期在查询和所有炒锅中手动删除了它。 这是我的最终代码:

    var plugins =
        from fi in di.GetFiles("*.dll").Where(p => p.Name.ToUpper() != "SDK.DLL")
        let asm = Assembly.LoadFrom(fi.FullName)
        from t in asm.GetExportedTypes()
        where t.GetInterface(typeof(iPluggin).Name) != null
        select asm.CreateInstance(t.FullName, true) as iPluggin;
    Project.ProcessList.AddRange(plugins);

暂无
暂无

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

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