Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C# 访问修饰符


访问修饰符

到目前为止,你已经相当熟悉在我们许多示例中出现的 public 关键字

public string color;

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

C# 具有以下访问修饰符

修饰符 描述
public 代码对所有类可见
private 代码仅在同一个类中可见
protected 代码在同一个类中或从该类继承的类中可见。你将在后面的章节中了解有关 继承 的更多信息
internal 代码仅在其自己的程序集中可见,但在另一个程序集中不可见。你将在后面的章节中了解有关此内容的更多信息

还有两种组合:protected internalprivate protected

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


private 修饰符

如果你使用 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' 由于其保护级别而无法访问
已分配字段 'Car.model',但其值从未使用过

自己试一试 »



public 修饰符

如果你使用 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
}

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.