如何将相同的PropertyInfo与不同的ReflectedType值进行比较?

ast*_*tef 5 .net c# reflection

这是一个简单的测试,证明了这个问题:

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
}
Run Code Online (Sandbox Code Playgroud)

我需要一个比较方法,它将确定这两个属性实际上代表相同的属性.这样做的正确方法是什么?

特别是我想检查属性是否实际上来自基类而不是以任何方式改变,例如override(with override int Foo),hidden(with new int Foo)属性,接口属性(即派生类中的显式实现ISome.Foo)或任何其他导致不调用的方式MyBase.Foo何时instanceOfDerived.Foo使用.

jga*_*fin 7

ReflectedType始终返回您要反思的类型.DeclaringType告诉我们声明属性的类型.所以你需要替换为:

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

用法:

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

编辑:删除了PropertyType检查作为评论中来自@Rob的建议.

  • 我会检查“PropertyInfo.DeclaringType”和“PropertyInfo.MetadataToken”。所以不可能有没有想到的边缘情况。 (3认同)