开发者

How do private fields work in derived classes?

When I inherit from a class such as Button, how do the properties of Button work in the derived class? The private fields of Button are not inherited in my derived class, but don't the properties need to still be there so that the public properties can access the internal private state? For example, how does the Location property work in the following example?

public class MyClass : Button
{
    MyClass()
   开发者_如何学C {
        this.Location = new System.Drawing.Point(134, 34);
    }
}

In the .NET source code, I see that Location is implemented as:

public Point Location
{
    get
    {
        return new Point(this.x, this.y);    // x is a private field
    }
    set
    {
        this.SetBounds(value.X, value.Y, 
                       this.width, this.height, 
                       BoundsSpecified.Location);
    }
}

I don't understand why the access to this.x and this.y doesn't cause an error in my derived class.


Being private just prevents code from being directly accessed from outside upon compilation. Indeed, it's possible through reflection to access private fields directly.

Hence private fields are inherited by derived class, but direct access to them is not.

This means that the defining class can control access to them and make sure that they are not set to invalid values, or that any work that needs to be done upon their changing is done, but the derived class can still make use of the way that they are used to implement protected and public members.


I'd like to suggest you do some studying on polymorphism and inheritance in C#. Here's a link on the MSDN site to get you started http://msdn.microsoft.com/en-us/library/ms173149.aspx

In a nutshell, when you inherit from a parent class, Button for example, the private members of Button are still accessible and used within the parent class, they don't get overridden or disappear. In the derived class, MyClass for example, none of the private members of Button are directly accessible (although they can be accessed via reflection). However, any public or protected members of Button are accessible in MyClass.

As a result, when MyClass is instantiated and used, all public methods and properties of both Button, and MyClass are accessible for use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜