受保护的关键字 C#

发布于 2024-09-17 09:16:27 字数 146 浏览 8 评论 0原文

我想知道 C# 中 protected 的含义是什么,为什么我们使用它,以及该关键字的好处?

例如

protected int currentColorIndex;

请详细说明。

I want to know what is the meaning of protected in C#, why we use it, and the benefit of the keyword?

For instance

protected int currentColorIndex;

Please elaborate.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

惯饮孤独 2024-09-24 09:16:27

每个人的答案都是相似的(定义和/或 MSDN 的摘录/链接),所以我会尝试回答您最初的 3 个问题:

含义:

任何标记为“受保护”的字段都意味着它只可见对于它自己和任何子级(从它继承的类)。您会注意到,在 ASP.NET Web 窗体代码隐藏模型中,事件处理程序(例如 Page_Load)被标记为“受保护”。这是因为 ASPX 标记文件实际上继承自代码隐藏文件(查看 @Page 指令来证明这一点)。

为什么使用它:

protected 可访问性修饰符的常见用途是让子级访问其父级属性。您可能有一个基类,许多子类都派生自该基类。这个基类可能有一个共同的属性。对于受保护的财产来说,这是一个很好的案例 - 促进公共逻辑的重用和集中维护。

好处:

类似于“我们为什么使用它?”的问题。但本质上它提供了对属性的粗粒度控制。你不能只考虑“当你使用 protected 时”。这更多的是选择何时使用哪个可访问性修饰符(私有、公共、内部、受保护)的情况。因此,其好处实际上与任何可访问性修饰符的好处相同 - 提供强大且一致的对象模型,最大限度地提高代码重用性并最大限度地减少与不正确公开的代码相关的安全风险。

希望有帮助。

Everyone's answer is similar (a definition and/or a excerpt/link to MSDN), so ill attempt to answer your original 3 questions:

The Meaning:

Any field marked with 'protected' means it is only visible to itself and any children (classes that inherit from it). You will notice in the ASP.NET Web Forms code behind model, event handlers (such as Page_Load) are marked 'protected'. This is because the ASPX Markup file actually inherits from the code-behind file (look at the @Page directive to prove this).

Why We Use It:

The common use of the protected accessibility modifier is to give children access to it's parents properties. You might have a base class for which many subclasses derive from. This base class may have a common property. This is a good case for a protected property - to facilitate the re-use and central maintenance of common logic.

The Benefit:

Kind of similar question to "why we use it?" But essentially it gives coarse-grained control over properties. You can't just think of "when you use protected". It's more a case of choosing when to use which accessibility modifier (private, public, internal, protected). So the benefit is really the same benefit of any accessibility modifier - provide a robust and consistent object model, maximising code re-use and minimizing security risks associated with incorrectly exposed code.

Hope that helps.

已下线请稍等 2024-09-24 09:16:27

正如其他人已经指出的:

受保护的关键字是成员
访问修饰符。受保护的成员是
在其类别内可访问
派生类实例。

这是一个小例子:

public class A
{
    protected string SomeString;
    public string SomeOtherString;
}

public class B : A
{
    public string Wrapped
    {
        get { return this.SomeString; }
    }
}

...

var a = new A();
var s = a.SomeOtherString; // valid
var s2 = a.SomeString; // Error

var b = new B();
var s3 = b.Wrapped; // valid

As others have already pointed out:

The protected keyword is a member
access modifier. A protected member is
accessible within its class and by
derived class instances.

Here is a small example:

public class A
{
    protected string SomeString;
    public string SomeOtherString;
}

public class B : A
{
    public string Wrapped
    {
        get { return this.SomeString; }
    }
}

...

var a = new A();
var s = a.SomeOtherString; // valid
var s2 = a.SomeString; // Error

var b = new B();
var s3 = b.Wrapped; // valid
笙痞 2024-09-24 09:16:27

“受保护的成员可以从
在它所在的类中
声明的,并且来自任何类
从声明的类派生
这位成员。”

请参阅

https://learn.microsoft .com/en-us/dotnet/csharp/language-reference/keywords/protected

"A protected member is accessible from
within the class in which it is
declared, and from within any class
derived from the class that declared
this member."

see

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected

双马尾 2024-09-24 09:16:27

直接来自 MSDN:

protected 关键字是成员访问修饰符。受保护的成员可以在其类内和派生类实例中访问。

来源

使用受保护意味着您可以拥有功能在可用于派生类的类中,但不可用于仅实例化该对象的类。

此页面比较了不同的访问修饰符解释了它们的含义,并给出了不同对象(枚举、类、接口和结构)的默认修饰符表。

Straight from the MSDN:

The protected keyword is a member access modifier. A protected member is accessible within its class and by derived class instances.

Source

Using protected means you can have functionality in a class that's available to derived classes, but not to classes that just instantiate the object.

This page compares the different access modifiers and explains what they mean and gives a table of the default modifiers for different objects (enum, class, interface and struct).

萝莉病 2024-09-24 09:16:27

另一个答案中提供了定义。为什么这样好呢?当 protected 为派生类提供对基类实现的访问时,您不必将数据/代码从基类复制到其派生类,而不会像 那样暴露于不受限制的外部使用。公开

Definition provided in another answer. Why is this good? You don't have to duplicate data/code from base class to its derived classes when protected offers them access to base class implementations, without the unwanted exposure to unrestricted external usage that would be implied by public.

分开我的手 2024-09-24 09:16:27

这意味着该字段仅对类本身和继承的类可见。

It means that the field is only visible to the class itself and inherited classes.

め七分饶幸 2024-09-24 09:16:27

这样想吧。一个类提供三个接口:

  1. 面向自身,可以完全访问内部实现细节(公共、受保护、私有方法和属性)。根据定义,你在课堂上做的任何事情都可能影响其他事情。
  2. 面向其客户端,只能访问公共方法和属性。您可以最小化类的公共接口,以最大程度地减少更改的意外后果:代码对内部了解得越少,您以后可以更自由地修改它们。
  3. 面向其后代,可以访问公共以及受保护的方法和属性。无论您对受保护的方法和公共方法做什么,不仅会影响客户端,还会影响修改类的基本功能的后代。 OO 是关于减少耦合并增加内聚类之间没有比继承关系更强的耦合(好吧,除了C++ 朋友,当然)!

第三个接口是 OO 中最难的一般设计挑战:什么可以合理地被重写(虚拟方法和属性),以及为了重写,还需要哪些其他功能(普通受保护方法和属性)?因为这是一个很大的挑战,所以默认情况下sealed类实际上是一个好主意,但对于 OO 初学者来说,这常常是违反直觉的,对他们来说,这似乎是一个不必要的障碍。

Think of it like this. A class presents three interfaces:

  1. Towards itself, with full access to internal implementation details (public, protected, private methods and attributes). By definition, anything you do in a class may affect anything else.
  2. Towards its clients, with access only to the public methods and attributes. You minimize the public interface of a class in order to minimize unexpected consequences of changes: the less code knows about your internals, the more freely you can modify them later.
  3. Towards its descendants, with access to the public and the protected methods and attributes. Whatever you do to protected and public methods will impact not only clients, but also descendants that modify the base functionality of your class. OO is about reducing coupling and increasing cohesion: there is no stronger coupling between classes than the inheritance relation (well, apart from the C++ friend, of course)!

The third interface is the hardest general design challenge in OO: what can reasonably be overridden (virtual methods and properties), and in order to override, what other functionality is needed (plain protected methods and attributes)? Because this is such a challenge, having classes sealed by default is actually a good idea, counterintuitive as it frequently seems to OO beginners, to whom it seems like an unnecessary handicap.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文