![](/img/trans.png)
[英]Looking for type inference in a generic IEqualityComparer over anonymous types
[英]How to make IEqualityComparer<Type> for generic types
我想要一個IEqualityComparer<Type>
,當且僅當兩個泛型類型相同而忽略泛型參數時,它返回true。 因此comparer.Equals(typeof(List<A>), typeof(List<B>))
應該返回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為null,則將拋出NRE,因此,如果您想要更強大的檢查,也可以添加null檢查。
public bool Equals(Type x, Type y)
{
var a = x.IsGenericType ? x.GetGenericTypeDefinition() : x;
var b = y.IsGenericType ? y.GetGenericTypeDefinition() : y;
return a == b;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.