gpt4 book ai didi

c# - Type.GetInterface 返回 null

转载 作者:行者123 更新时间:2023-11-30 22:20:52 25 4
gpt4 key购买 nike

我的问题是,我从历史记录中得到的结果与我们较旧的 DLL 不同,当时变化很小,而且我不知道这些变化与显示的错误有何关联。

这是我们的 SecurityPluginServices.dll 模块中方法的一部分,它实质上是将插件添加到列表中,以便主程序可以使用它们。

它获取一组文件夹中的所有 DLL,然后针对每个 DLL 运行下面的代码。

private void AddPlugin(string FileName, LoggingUtilities.Source source)
{
//Create a new assembly from the plugin file we're adding..
Assembly pluginAssembly = Assembly.LoadFrom(FileName);

try
{
//Next we'll loop through all the Types found in the assembly
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic) //Only look at public types
{
if (!pluginType.IsAbstract) //Only look at non-abstract types
{
//Gets a type object of the interface we need the plugins to match
Type typeInterface = pluginType.GetInterface("SecurityInterface.ISecurityPlugin", true);

//Make sure the interface we want to use actually exists
if (typeInterface != null)
{
// Do work here
}

typeInterface = null; //Mr. Clean
}
}
}

pluginAssembly = null; //more cleanup
}
catch (ReflectionTypeLoadException ex1)
{
Console.WriteLine(ex1.Message);
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message);
}
}

我遇到的问题是每次到达 Type typeInterface = pluginType.GetInterface("SecurityInterface.ISecurityPlugin", true);它总是返回空值。我需要加载的插件用于 NTLM 和 LDAP,它们在许多版本中变化很小,只添加了几个额外的属性和方法,与实现的接口(interface)无关。我已经在 ILDASM 中打开了较新的插件 DLL 和其中一个较旧的插件的副本,它们似乎都包含有关 SecurityInterface.ISecurityPlugin 的相同信息。那.GetInterface方法正在求。

Newer LdapSecurity

Older LdapSecurity

最佳答案

建议:

Type typeInterface = pluginType.GetInterface("SecurityInterface.ISecurityPlugin", true);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

将其更改为 fully-qualified type name ,即包含包含您的接口(interface)类型的程序集。

(如果您现在说在两个不同的程序集中有两个同名的不同类型,因此不能包括一个明确的程序集名称,这很可能是问题的原因。)

解释:

我的另一个回答让我怀疑是什么导致了您的问题。一般来说,typeof(T) 会强制您为包含 T 的程序集添加对项目的程序集引用。否则编译会失败。另一方面,类型名称的文本提及,例如 Type.GetType("T") 不强制执行编译时程序集引用......但它们仍然必须解析为类型实例在运行时。因此,如果省略程序集名称,则需要记住 .NET 如何将 T 映射到特定程序集。

回到你的问题。首先,请注意您没有使用完全限定的类型名称:

Type typeInterface = pluginType.GetInterface("SecurityInterface.ISecurityPlugin", true);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

您只指定命名空间和类型名称,而不是包含您的接口(interface)类型的程序集。会不会是接口(interface)类型被定义了不止一次,即在不同的程序集中,并且您提到的那个类型名称被解析为输入了错误的程序集?

让我们简要地看一下 MSDN documentation for Type.GetType(string) method ,其中对字符串参数的描述如下:

"The assembly-qualified name of the type to get. […] If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace."

如果同样适用于您正在使用的 Type.GetInterface(string, bool) 方法怎么办?如果您当前正在执行的程序集确实包含该名称的类型怎么办?那么这就是 pluginType 将被检查的类型...但它可能是与您的插件不同的 ISecurityPlugin 接口(interface)类型(尽管名称相同)类实际实现。

关于c# - Type.GetInterface 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14757298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com