物业隐藏和反射(C#)反射、物业

2023-09-03 15:40:55 作者:当蜂蜜爱上蜜糖

在声明派生类相匹配的基类的属性的名称的属性隐藏它(除非它覆盖了它与覆盖关键字)。无论是基类和派生类的属性将 Type.GetProperties()返回,如果它们的类型不匹配。但是,如果它们的类型的执行的匹配,只有惊人的派生类的属性返回。例如:

Declaring a property in a derived class that matches the name of a property in the base class "hides" it (unless it overrides it with the override keyword). Both the base and derived class properties will be returned by Type.GetProperties() if their types don't match. However, if their types do match, shockingly only the derived class's property is returned. For instance:

class A
{
    protected double p;
    public int P { get { return (int)p; } set { p = value; } }
}
class B : A
{
    public new int P { get { return (int)p; } set { p = value; } }
}
class C : B
{
    public new float P { get { return (float)p; } set { p = value; } }
}

调用的typeof(C).GetProperties()只会返回BP和CP是否有可能调用的GetProperties,()在返回三个办法?这里有几乎可以肯定的方式通过遍历继承层次做到这一点,但它是一个清洁的解决方案?

Calling typeof(C).GetProperties() will only return B.P and C.P. Is it possible to call GetProperties() in a way that returns all three? There is almost certainly a way to do it by traversing the inheritance hierarchy, but is there a cleaner solution?

推荐答案

GetProperties中被定义为所有类型的公共属性。

GetProperties is defined as all public properties of the type.

您可以得到他们获取并使用设置方法:

You could get their get and set methods using:

typeof(C).GetMethods()
         .Where(m => m.Name.StartsWith("set_") || m.Name.StartsWith("get_"))

尽管这似乎是一个坏主意,相比下降了继承层次结构来获得属性。

Although this seems like a bad idea, compared to going down the inheritance hierarchy to get the properties.