到现在为止,你已经非常熟悉了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 internal
和private protected
。
现在,让我们重点关注public
和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' 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
}
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!