我有一些比较两个PropertyInfo对象是否相等的代码,使用Equals()方法。通常情况下这种方法是可行的,但我遇到了一个奇怪的问题:对于同一个属性反射得到的两个PropertyInfo对象,它们却不相等:
PropertyInfo prop1, prop2; // both are public and not static
Console.WriteLine(prop1 == prop2); // false ???
Console.WriteLine(Equals(prop1, prop2)); // false ???
Console.WriteLine(prop1.DeclaringType == prop2.DeclaringType); // true
Console.WriteLine(prop1.ReturnType == prop2.ReturnType); // true
Console.WriteLine(prop1.Name == prop2.Name); // true
Console.WriteLine(prop1.DeclaringType.GetProperties().Contains(prop1)); // true
Console.WriteLine(prop2.DeclaringType.GetProperties().Contains(prop2)); // false ???
似乎 PropertyInfo 实际上没有实现 Equals() 方法,但我认为 .NET 会缓存反射成员,以便始终返回相同的实例。你经常看到 a.GetType() == b.GetType()。PropertyInfos 不是这种情况吗?
其他一些注意事项: - 在 .NET 4、VS2012、x86 构建目标下运行 NUnit 测试时发生了这种奇怪的情况 - 这种比较方式并不适用于我们比较的所有属性,但在一个属性上始终失败。
有人能解释这种行为吗?
编辑:如果有人感兴趣,这里是我编写的用于比较 MemberInfos 的 EqualityComparison 函数:
public class MemberEqualityComparer : EqualityComparer<MemberInfo> {
public override bool Equals(MemberInfo @this, MemberInfo that) {
if (@this == that) { return true; }
if (@this == null || that == null) { return false; }
// handles everything except for generics
if (@this.MetadataToken != that.MetadataToken
|| !Equals(@this.Module, that.Module)
|| this.Equals(@this.DeclaringType, that.DeclaringType))
{
return false;
}
bool areEqual;
switch (@this.MemberType)
{
// constructors and methods can be generic independent of their types,
// so they are equal if they're generic arguments are equal
case MemberTypes.Constructor:
case MemberTypes.Method:
var thisMethod = @this as MethodBase;
var thatMethod = that as MethodBase;
areEqual = thisMethod.GetGenericArguments().SequenceEqual(thatMethod.GetGenericArguments(),
this);
break;
// properties, events, and fields cannot be generic independent of their types,
// so if we've reached this point without bailing out we just return true.
case MemberTypes.Property:
case MemberTypes.Event:
case MemberTypes.Field:
areEqual = true;
break;
// the system guarantees reference equality for types, so if we've reached this point
// without returning true the two are not equal
case MemberTypes.TypeInfo:
case MemberTypes.NestedType:
areEqual = false;
break;
default:
throw new NotImplementedException(@this.MemberType.ToString());
}
public override int GetHashCode(MemberInfo memberInfo) {
if (memberInfo == null) { return 0; }
var hash = @this.MetadataToken
^ @this.Module.GetHashCode()
^ this.GetHashCode(@this.DeclaringType);
return hash;
}
}