.net 中的受保护和私有声明

发布于 2024-11-05 04:47:38 字数 43 浏览 2 评论 0原文

除了无法在类外部访问之外,受保护声明和私有声明之间是否有任何区别/优点?

Are there any difference/advantages between protected and private declaration apart from it not being accessible outside the class.

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

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

发布评论

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

评论(5

你的心境我的脸 2024-11-12 04:47:38

这些是辅助功能修饰符 - 这就是他们的重点。

These are accessibility modifiers - that's their point.

狂之美人 2024-11-12 04:47:38

private 成员只能从类内部访问,protected 成员也可以由继承自它的类访问。

private members are only accessible from within the class, protected members are also accessible by classes that inherit from it.

东走西顾 2024-11-12 04:47:38

从 MSDN 中查看此示例:

class A 
{
   protected int x = 123;
}

class B : A 
{
   void F() 
   {
      A a = new A();  
      B b = new B();  
      a.x = 10;   // Error
      b.x = 10;   // OK
   }
}

See the ax throws an error because you are attempts to access the property from the external of the class (calling the prop inside A from inside the class B).但 bx 是可以的,因为你是从 B 内部调用它的。有意义吗?

Check out this example from the MSDN:

class A 
{
   protected int x = 123;
}

class B : A 
{
   void F() 
   {
      A a = new A();  
      B b = new B();  
      a.x = 10;   // Error
      b.x = 10;   // OK
   }
}

See the a.x throws an error because you are trying to access the property from outside the class (calling the prop within A from inside the class B). But b.x is ok, because you are calling it from inside B. Make sense?

温柔嚣张 2024-11-12 04:47:38

具有protected访问修饰符的成员可以在派生类中访问。而那些拥有 private 访问修饰符的人只能在同一个类中访问。

了解访问修饰符

Members that have the protected access modifier are accessible in the derived classes. While those who have the private access modifier are accessible only within the same class.

Read about access modifiers.

南…巷孤猫 2024-11-12 04:47:38

struct 成员只能声明为 publicprivateinternal

class 成员可以声明为 publicprotectedinternalprotectedinternal、或私有

MSDN 上的访问修饰符

struct members can only be declared as public, private or internal.

class members can be declared as public, protected internal, protected, internal, or private.

Access Modifiers on MSDN

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