C# 访问修饰符
最后修改于 2024 年 1 月 21 日
在本文中,我们将展示如何在 C# 中控制方法和成员字段的可见性。
访问修饰符 设置方法和成员字段的可见性。 C# 有四个基本的访问修饰符:public
、protected
、private
和 internal
。 public
成员可以从任何地方访问。 protected
成员只能在类本身以及继承类和父类中访问。 private
成员仅限于包含类型,例如,仅在其类或接口中。 internal
成员可以从同一程序集(exe 或 DLL)中访问。
还有两个修饰符的组合:protected internal
和 private protected
。 protected internal
类型或成员可以被声明它的程序集中的任何代码访问,或者从另一个程序集中的派生类中访问。 private protected
类型或成员只能在其声明的程序集中,通过同一类或从该类派生的类型中的代码访问。
访问修饰符保护数据免受意外修改。 它们使程序更加健壮。
类别 | 当前程序集 | 派生类型 | 当前程序集中的派生类型 | 整个程序 | |
---|---|---|---|---|---|
public | + | + | + | + | + |
protected | + | o | + | + | o |
internal | + | + | o | o | o |
private | + | o | o | o | o |
protected internal | + | + | + | + | o |
private protected | + | o | o | + | o |
上表总结了 C# 访问修饰符(+ 可访问,o 不可访问)。
C# 访问修饰符示例
在下面的示例中,我们使用 public 和 private 访问修饰符。
var p = new Person(); p.name = "Jane"; p.SetAge(17); Console.WriteLine($"{p.name} is {p.GetAge()} years old"); class Person { public string name; private int age; public int GetAge() { return this.age; } public void SetAge(int age) { this.age = age; } }
在上面的程序中,我们有两个成员字段。 一个声明为 public,另一个声明为 private。
public int GetAge() { return this.age; }
如果成员字段是 private
,则访问它的唯一方法是通过方法。 如果我们想在类外修改一个属性,该方法必须声明为 public
。 这是数据保护的一个重要方面。
public void SetAge(int age) { this.age = age; }
SetAge
方法使我们能够从类定义外部更改 private
age 变量。
var p = new Person(); p.name = "Jane";
我们创建一个新的 Person
类的实例。 因为 name 属性是 public
,所以我们可以直接访问它。 但是,不建议这样做。
p.SetAge(17);
SetAge
方法修改 age 成员字段。 由于它被声明为 private
,因此无法直接访问或修改。
Console.WriteLine($"{p.name} is {p.GetAge()} years old");
最后,我们访问两个成员来构建一个字符串。
$ dotnet run Jane is 17 years old
C# 访问修饰符示例 II
具有 private
访问修饰符的成员字段不会被派生类继承。
var derived = new Derived(); derived.info(); class Base { public string name = "Base"; protected int id = 5323; private bool isDefined = true; } class Derived : Base { public void info() { Console.WriteLine("This is Derived class"); Console.WriteLine("Members inherited"); Console.WriteLine(this.name); Console.WriteLine(this.id); // Console.WriteLine(this.isDefined); } }
在前面的程序中,我们有一个从 Base
类继承的 Derived
类。 Base
类有三个成员字段。 所有字段都具有不同的访问修饰符。 isDefined 成员不会被继承。 private
修饰符阻止了这种情况。
class Derived : Base
类 Derived
从 Base
类继承。 要从另一个类继承,我们使用冒号 (:) 运算符。
Console.WriteLine(this.name); Console.WriteLine(this.id); // Console.WriteLine(this.isDefined);
public
和 protected
成员被 Derived
类继承。 它们可以被访问。 private
成员不被继承。 访问成员字段的行被注释掉了。 如果我们取消注释该行,代码将无法编译。
$ dotnet run ... warning CS0414: The field 'Base.isDefined' is assigned but its value is never used ... This is Derived class Members inherited Base 5323
来源
在本文中,我们使用了 C# 访问修饰符。
作者
列出所有 C# 教程。