问题
This is a followup to this question: Lambda expression not returning expected MemberInfo
class Human
{
public string name { get; set; }
}
class Man : Human
{
}
var m1 = typeof(Human).GetProperty("name");
var m2 = typeof(Man).GetProperty("name");
//m1 != m2 why?
The same holds for MethodInfo
s.
I can understand there has to be a difference when Human
is an interface, or when name
of Human
is abstract/virtual. But why is it so for sealed types? Isn't name
of Man
exactly name
of Human
?
Clarification: As Jon says their ReflectedType
s are different. ReflectedType
in equality should come handy when deciding equality of interface members or overridden members since they are different. But I don't think it should be considered for deciding equality of simple cases like above. May be the design team wanted to be consistent. Just wondering what rationale drove framework designers to consider ReflectedType
property in deciding equality of same member spanning over multiple classes.
回答1:
They differ in their ReflectedType property:
The ReflectedType property retrieves the Type object that was used to obtain this instance of MemberInfo. This may differ from the value of the DeclaringType property if this MemberInfo object represents a member that is inherited from a base class.
So if you print out m1.ReflectedType
, it should print Human
. If you print out m2.ReflectedType
, it should print Man
.
EDIT: In terms of why the equality operator is implemented this way: it's always a delicate design decision to work out what ==
should mean, in the case where there may be distinguishable but not "primary" differences between objects. This is where providing different IEqualityComparer
implementations is useful, but of course that doesn't work for the operators themselves.
In general, if x == y
is true then it's quite unusual for x.Foo
to be different to y.Foo
for any property. I can't immediately think of any cases where that occurs in the framework.
来源:https://stackoverflow.com/questions/16276271/why-is-a-member-of-base-class-different-from-the-same-member-in-derived-class