比较两个相等的System.Type失败



我制作了这个扩展方法来检查一个类型是否实现了接口。为了使其正常工作,它需要比较两种类型。然而,这种比较似乎并不奏效:

public static bool ImplementsInterface(this Type type, Type testInterface)
{
if (testInterface.GenericTypeArguments.Length > 0)
{
return testInterface.IsAssignableFrom(type);
}
else
{
foreach (var @interface in type.GetInterfaces())
{
// This doesn't always work:
if (@interface == testInterface)
// But comparing the names instead always works!
// if (@interface.Name == testInterface.Name)
{
return true;
}
}
return false;
}
}

这是我的比较失败的情况:

public static class TestInterfaceExtensions
{
interface I1 { }
interface I2<T> : I1 { }
class Class1Int : I2<int> { }
[Fact]
public void ImplementsInterface()
{
Assert.True(typeof(Class1Int).ImplementsInterface(typeof(I2<>)));
}
}

正如评论中提到的,如果我比较类型名称,那么它总是按预期工作。我想知道这里发生了什么。

如果接口是泛型的,则需要将其与泛型类型定义进行比较:

public static bool ImplementsInterface(this Type type, Type testInterface)
{
if (testInterface.GenericTypeArguments.Length > 0)
{
return testInterface.IsAssignableFrom(type);
}
else
{
foreach (var @interface in type.GetInterfaces())
{
var compareType = @interface.IsGenericType
? @interface.GetGenericTypeDefinition()
: @interface;
if (compareType == testInterface)
{
return true;
}
}
return false;
}
}

这适用于一堆测试用例:

Console.WriteLine(typeof(Class1Int).ImplementsInterface(typeof(I2<>)));     // True
Console.WriteLine(typeof(Class1Int).ImplementsInterface(typeof(I2<int>)));  // True
Console.WriteLine(typeof(Class1Int).ImplementsInterface(typeof(I2<bool>))); // False
Console.WriteLine(typeof(Class1Int).ImplementsInterface(typeof(I1)));       // True
Console.WriteLine(typeof(Class1Int).ImplementsInterface(typeof(I3)));       // False

现场示例:https://dotnetfiddle.net/bBslxH

最新更新