gpt4 book ai didi

.net - 私有(private)字段如何在派生类中工作?

转载 作者:行者123 更新时间:2023-12-04 06:31:12 24 4
gpt4 key购买 nike

当我从 Button 等类继承时,Button的属性怎么办?在派生类中工作? Button 的私有(private)字段没有在我的派生类中继承,但属性是否还需要存在以便公共(public)属性可以访问内部私有(private)状态?例如,Location 如何以下示例中的属性工作?

public class MyClass : Button
{
MyClass()
{
this.Location = new System.Drawing.Point(134, 34);
}
}

在 .NET 源代码中,我看到 Location实现为:
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);
}
}

我不明白为什么访问 this.xthis.y不会在我的派生类中导致错误。

最佳答案

私有(private)只是防止代码在编译时直接从外部访问。实际上,可以通过反射直接访问私有(private)字段。

因此私有(private)字段 由派生类继承,但不能直接访问它们。

这意味着定义类可以控制对它们的访问,并确保它们没有被设置为无效值,或者在更改它们时需要完成的任何工作都已完成,但派生类仍然可以使用它们用于实现 protected 和公共(public)的成员。

关于.net - 私有(private)字段如何在派生类中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5392764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com