Assembly.CreateInstance类型转换返回null

时间:2012-09-14 17:54:29

标签: c# .net-assembly

我正在尝试在运行时加载和使用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。 知道为什么吗?

2 个答案:

答案 0 :(得分:0)

我做了类似的事情:

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

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

答案 1 :(得分:0)

麻烦解决了,我不明白。

定义de interface(SDK.dll)的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);
相关问题