Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

.net - Property hiding and reflection (C#)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...