C# 访问修饰符


访问修饰符

到现在为止,你已经非常熟悉了public在我们的许多示例中出现的关键字:

public string color;

这个public关键字是一个访问修饰符,用于设置类、字段、方法和属性的访问级别/可见性。

C# 具有以下访问修饰符:

Modifier Description
public The code is accessible for all classes
private The code is only accessible within the same class
protected The code is accessible within the same class, or in a class that is inherited from that class. You will learn more about inheritance in a later chapter
internal The code is only accessible within its own assembly, but not from another assembly. You will learn more about this in a later chapter

还有两种组合:protected internalprivate protected

现在,让我们重点关注publicprivate修饰符。


私有修改器

如果您声明一个字段private访问修饰符,只能在同一个类中访问:

示例

class Car
{
  private string model = "Mustang";

  static void Main(string[] args)
  {
    Car myObj = new Car();
    Console.WriteLine(myObj.model);
  }
}

输出将是:

Mustang

亲自试一试 »

如果你尝试在类之外访问它,将会出现错误:

示例

class Car
{
  private string model = "Mustang";
}

class Program
{
  static void Main(string[] args)
  {
    Car myObj = new Car();
    Console.WriteLine(myObj.model);
  }
}

输出将是:

'Car.model' is inaccessible due to its protection level
The field 'Car.model' is assigned but its value is never used

亲自试一试 »



公共修改器

如果您声明一个字段public访问修饰符,所有类都可以访问:

示例

class Car
{
  public string model = "Mustang";
}

class Program
{
  static void Main(string[] args)
  {
    Car myObj = new Car();
    Console.WriteLine(myObj.model);
  }
}

输出将是:

Mustang

亲自试一试 »


为什么使用访问修饰符?

控制类成员的可见性(每个类和类成员的安全级别)。

实现 封装 - 这是确保敏感数据对用户隐藏。这是通过将字段声明为private。您将在下一章中了解更多相关内容。

笔记:默认情况下,类的所有成员都是private如果您不指定访问修饰符:

示例

class Car
{
  string model;  // private
  string year;   // private
}