首页 技术 正文
技术 2022年11月16日
0 收藏 888 点赞 4,094 浏览 766 个字

protected(C# 参考)

protected 关键字是一个成员访问修饰符。 受保护成员在其所在的类中可由派生类实例访问。

示例
只有在通过派生类访问时,基类的受保护成员在派生类中才是可访问的。 例如,请看以下代码段:
C#

class A
{
protected int x = ;
}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 = ;
}
}

语句 a.x = 10 生成错误,因为它是在静态方法 Main 中生成的,而不是类 B 的实例。

结构成员无法受保护,因为无法继承结构。
此示例中,DerivedPoint 类派生自 Point。 因此,可以从派生类直接访问基类的受保护成员。
C#

    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 = ;
dpoint.y = ;
Console.WriteLine("x = {0}, y = {1}", dpoint.x, dpoint.y);
}
}
// Output: x = 10, y = 15

如果将 x 和 y 的访问级别更改为 private,编译器将发出错误信息:
‘Point.y’ is inaccessible due to its protection level.
‘Point.x’ is inaccessible due to its protection level.

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,903
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,427
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,244
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,057
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,687
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,726