How to compare same PropertyInfo with different Re

2019-06-25 13:25发布

问题:

Here's a simple test demonstrating the problem:

class MyBase { public int Foo { get; set; } }    
class MyClass : MyBase { }    
[TestMethod]
public void TestPropertyCompare()
{
    var prop1 = typeof(MyBase).GetProperty("Foo");
    var prop2 = typeof(MyClass).GetProperty("Foo");
    Assert.IsTrue(prop1 == prop2); // fails
    //Assert.IsTrue(prop1.Equals(prop2)); // also fails
}

I need a comparing method which will determine that these two properties are actually represent the same property. What is the correct way of doing this?

In particular I want to check if property actually comes from base class and not altered in any way like overriden (with override int Foo), hidden (with new int Foo) properties, interface properties (i.e. explicit implementation in derived class ISome.Foo) or any other way that lead to not calling MyBase.Foo when instanceOfDerived.Foo is used.

回答1:

ReflectedType always return the type that you do reflection on. DeclaringType tells which type the property is declared in. So you equal check need to be replaced with:

public static class TypeExtensions
{
    public static bool PropertyEquals(this PropertyInfo property, PropertyInfo other)
    {
         return property.DeclaringType == other.DeclaringType
                    && property.Name == other.Name;
    }
}

Usage:

var prop1 = typeof(MyBase).GetProperty("Foo");
var prop2 = typeof(MyClass).GetProperty("Foo");
var isSame = prop1.PropertyEquals(prop2); //will return true

Edit: Removed The PropertyType check as suggestion from @Rob in the comments.