如何将相同的PropertyInfo与不同的ReflectedType值进行比较? [英] How to compare same PropertyInfo with different ReflectedType values?

查看:35
本文介绍了如何将相同的PropertyInfo与不同的ReflectedType值进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

特别是我想检查属性是否确实来自基类,并且是否以覆盖(使用 override int Foo ),隐藏(使用 new int Foo >)属性,接口属性(即派生类 ISome.Foo 中的显式实现)或任何其他导致 instanceOfDerived.Foo不调用 MyBase.Foo 的方式.

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.

推荐答案

ReflectedType 始终返回进行反射的类型. DeclaringType 告诉您声明属性的类型.因此,等价支票需要替换为:

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;
    }
}

用法:

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

作为建议,从@Rob中删除了PropertyType检查.

这篇关于如何将相同的PropertyInfo与不同的ReflectedType值进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆