如何为泛型制作 IEqualityComparer<Type>
How to make IEqualityComparer<Type> for generic types
我想要一个 IEqualityComparer<Type>
当且仅当两个泛型类型相同且忽略泛型参数时 return 为真。所以 comparer.Equals(typeof(List<A>), typeof(List<B>))
应该 return true
.
我正在做比较 Name
:
public class GenericTypeEqualityComparer : IEqualityComparer<Type>
{
public bool Equals(Type x, Type y)
{
return x.Name == y.Name;
}
public int GetHashCode(Type obj)
{
return obj.Name.GetHashCode();
}
}
存在一些误报案例(命名空间问题等)。我不知道还能做什么。
这是一个考虑到通用性的检查。如果 x 或 y 为空,它会抛出一个 NRE,所以如果你想要一个更健壮的检查,也添加一个空检查。
public bool Equals(Type x, Type y)
{
var a = x.IsGenericType ? x.GetGenericTypeDefinition() : x;
var b = y.IsGenericType ? y.GetGenericTypeDefinition() : y;
return a == b;
}
我想要一个 IEqualityComparer<Type>
当且仅当两个泛型类型相同且忽略泛型参数时 return 为真。所以 comparer.Equals(typeof(List<A>), typeof(List<B>))
应该 return true
.
我正在做比较 Name
:
public class GenericTypeEqualityComparer : IEqualityComparer<Type>
{
public bool Equals(Type x, Type y)
{
return x.Name == y.Name;
}
public int GetHashCode(Type obj)
{
return obj.Name.GetHashCode();
}
}
存在一些误报案例(命名空间问题等)。我不知道还能做什么。
这是一个考虑到通用性的检查。如果 x 或 y 为空,它会抛出一个 NRE,所以如果你想要一个更健壮的检查,也添加一个空检查。
public bool Equals(Type x, Type y)
{
var a = x.IsGenericType ? x.GetGenericTypeDefinition() : x;
var b = y.IsGenericType ? y.GetGenericTypeDefinition() : y;
return a == b;
}