简体   繁体   English

比较两个 System.Type 是否相等失败?

[英]Comparing two System.Type for equality fails?

I've made this extension method to check if a type implements an interface.我做了这个扩展方法来检查一个类型是否实现了一个接口。 For it to work correctly it needs to compare 2 types.为了让它正常工作,它需要比较两种类型。 This comparison however doesn't seem to work realiably:然而,这种比较似乎并不可靠:

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

This is the case where my comparison fails:这是我的比较失败的情况:

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

As mentioned in the comment, if I compare the type names then it always works as expected.正如评论中提到的,如果我比较类型名称,那么它总是按预期工作。 I would like to know what's going on here.我想知道这里发生了什么。

If the interface is generic you need to be comparing back to the generic type definition:如果接口是泛型的,则需要与泛型类型定义进行比较:

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

This works for a bunch of test cases:这适用于一堆测试用例:

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

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

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

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