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

2024-04-17

这是一个演示该问题的简单测试:

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
}

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

特别是,我想检查属性是否实际上来自基类,并且没有以任何方式更改,例如重写(使用override int Foo),隐藏(与new int Foo)属性、接口属性(即派生类中的显式实现ISome.Foo)或任何其他导致不调用的方式MyBase.Foo when instanceOfDerived.Foo用来。


ReflectedType始终返回您进行反射的类型。DeclaringType另一方面,告诉您该属性实际上是在哪种类型上声明的。所以你需要做的是:

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

编辑:删除了评论中@Rob 建议的 PropertyType 检查。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何比较相同的 PropertyInfo 与不同的 ReflectedType 值? 的相关文章

随机推荐