简述 private、protected、public、internal 修饰符的作用域
时间: 2025-02-04 20:32:44 浏览: 34
### C# 访问修饰符的作用域解释
#### private 修饰符
`private` 修饰符定义的成员仅能在声明它的类内部访问。这意味着即使派生自该类的子类也无法访问 `private` 成员[^2]。
```csharp
class Vehicle {
private string model;
}
```
#### protected 修饰符
`protected` 关键字指定的成员可由其所在类及其任何派生类访问。这使得基类能够向子类公开某些实现细节而不对外界开放[^1]。
```csharp
class Engine {
protected int _rpm;
protected void Burn(int amount) {
// Implementation here...
}
}
class Car : Engine {
public void Start() {
this._rpm = 800; // Accessible because of inheritance.
base.Burn(5); // Also accessible through 'base' keyword.
}
}
```
#### public 修饰符
当使用 `public` 来限定成员时,它意味着没有任何访问限制;也就是说,此类或结构中的公共成员可以从程序内的任意位置被访问到[^4]。
```csharp
public class Program {
static void Main(string[] args) {
var car = new Car();
Console.WriteLine(car.GetType().Name);
}
}
```
#### internal 修饰符
带有 `internal` 的成员可以在同一程序集(即同一个项目)内自由访问,但在外部则无法触及。这对于希望保持组件间接口清晰的应用特别有用。
```csharp
internal class InternalClass {
public void DoSomething() {}
}
// Within the same assembly/project:
var instance = new InternalClass();
instance.DoSomething(); // This works fine within the project boundary.
// Outside the assembly/project would result in compile-time error.
```
阅读全文
相关推荐














