我已经编写了这个扩展方法来检查一个类型是否实现了一个接口。为了使它能够正确地工作,它需要比较两个类型。然而,这种比较似乎并不可靠:
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<>)));
}
}
正如评论中提到的,如果我比较类型名称,它总是按预期工作。我想知道这里发生了什么。