• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

protected(C#Reference)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

https://msdn.microsoft.com/en-us/library/bcd5672a.aspx

The protected keyword is a member access modifier.

A protected member is accessible within its class and by derived class instances.

For a comparison of protected with the other access modifiers, see Accessibility Levels.

 

Example

A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type.

For example, consider the following code segment:

class A
{
    protected int x = 123;
}

class B : A
{
    static void Main()
    {
        A a = new A();
        B b = new B();

        // Error CS1540, because x can only be accessed by
        // classes derived from A.
        // a.x = 10; 

        // OK, because this class derives from A.
        b.x = 10;
    }
}

The statement a.x = 10 generates an error because it is made within the static method Main, and not an instance of class B.

Struct members cannot be protected because the struct cannot be inherited.

 

Example

In this example, the class DerivedPoint is derived from Point.

Therefore, you can access the protected members of the base class directly from the derived class.

class Point 
{
    protected int x; 
    protected int y;
}

class DerivedPoint: Point 
{
    static void Main() 
    {
        DerivedPoint dpoint = new DerivedPoint();

        // Direct access to protected members:
        dpoint.x = 10;
        dpoint.y = 15;
        Console.WriteLine("x = {0}, y = {1}", dpoint.x, dpoint.y); 
    }
}
// Output: x = 10, y = 15

If you change the access levels of x and y to private, the compiler will issue the error messages:

'Point.y' is inaccessible due to its protection level.

'Point.x' is inaccessible due to its protection level.

 

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

 

 

See Also

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#字符串首字符大写发布时间:2022-07-14
下一篇:
浅谈w3c标准发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap