在 C# 中,访问修饰符用于定义类、方法、属性和其他成员的可访问范围。理解并正确使用这些修饰符对于编写安全、模块化和易于维护的代码至关重要。本文将详细介绍 public
、private
、protected
和 internal
四种访问修饰符,并通过丰富的示例和详细的注释来说明它们的使用方式和应用场景。
怎么说呢,实际项目开发中基本一路public到头了,这肯定是个坏习惯。
public
访问修饰符public
成员,无论是在同一个程序集还是不同的程序集。public
。C#namespace App04
{
public class Calculator
{
// 公有方法,可以被任何代码访问
public int Add(int a, int b)
{
return a + b;
}
}
internal class Program
{
static void Main(string[] args)
{
// 使用 Calculator 类
Calculator calculator = new Calculator();
int result = calculator.Add(5, 3); // 输出:8
Console.WriteLine($"结果:{result}");
}
}
}
解释:Add
方法被声明为 public
,因此可以在类的外部直接调用。
private
访问修饰符private
成员只能在其包含的类或结构体内部访问。C#public class BankAccount
{
// 私有字段,存储账户余额
private decimal balance;
// 构造函数,初始化余额
public BankAccount(decimal initialBalance)
{
balance = initialBalance;
}
// 公有方法,存款
public void Deposit(decimal amount)
{
balance += amount;
}
// 公有方法,取款
public bool Withdraw(decimal amount)
{
if (amount <= balance)
{
balance -= amount;
return true;
}
else
{
Console.WriteLine("余额不足!");
return false;
}
}
// 公有方法,获取余额
public decimal GetBalance()
{
return balance;
}
}
// 使用 BankAccount 类
BankAccount account = new BankAccount(1000);
account.Deposit(500);
bool success = account.Withdraw(200);
Console.WriteLine($"操作成功:{success}");
Console.WriteLine($"当前余额:{account.GetBalance()}");
解释:balance
字段被声明为 private
,只能在 BankAccount
类内部访问。外部代码需要通过公有方法如 Deposit
、Withdraw
和 GetBalance
来操作余额。
protected
访问修饰符protected
成员可以在其包含的类以及派生类中访问,但不能在其他地方访问。C#namespace App04
{
public class Person
{
// 受保护字段,存储姓名
protected string Name;
// 公有构造函数,初始化姓名
public Person(string name)
{
Name = name;
}
// 受保护方法,显示姓名
protected void DisplayName()
{
Console.WriteLine($"姓名:{Name}");
}
}
// 派生类 Student,继承自 Person
public class Student : Person
{
// 公有字段,存储学号
public int StudentID;
// 构造函数,初始化姓名和学号
public Student(string name, int studentID) : base(name)
{
StudentID = studentID;
}
// 公有方法,显示学生信息
public void DisplayStudentInfo()
{
// 调用受保护的 DisplayName 方法
DisplayName();
Console.WriteLine($"学号:{StudentID}");
}
}
internal class Program
{
static void Main(string[] args)
{
// 使用 Student 类
Student student = new Student("张三", 1001);
student.DisplayStudentInfo();
}
}
}
解释:Name
字段和 DisplayName
方法被声明为 protected
,只能在 Person
类及其派生类 Student
中访问。Student
类通过继承,访问了这些受保护成员。
internal
访问修饰符internal
成员只能在同一程序集内访问,程序集外部无法访问。C#// 假设以下代码在名为 MyLibrary 的程序集内
// InternalHelper 类,仅在程序集内可见
internal class InternalHelper
{
// internal 方法,可以在程序集内访问
internal static void DoSomething()
{
Console.WriteLine("InternalHelper 正在执行操作");
}
}
// 公有类 PublicApi
public class PublicApi
{
// 公有方法,调用 InternalHelper
public void PerformAction()
{
InternalHelper.DoSomething();
}
}
// 在同一程序集内使用 PublicApi
PublicApi api = new PublicApi();
api.PerformAction();
解释:InternalHelper
类被声明为 internal
,只能在 MyLibrary
程序集内访问。PublicApi
类可以访问 InternalHelper
,因为它们在同一个程序集内。
protected internal
C#public class BaseClass
{
// 受保护的 internal 成员
protected internal int Value = 42;
}
// 在同一程序集内的类
public class SameAssemblyClass
{
public void AccessValue()
{
BaseClass baseObj = new BaseClass();
Console.WriteLine($"Value: {baseObj.Value}");
}
}
// 在其他程序集中的派生类
public class DerivedClass : BaseClass
{
public void ShowValue()
{
Console.WriteLine($"Value: {Value}");
}
}
private protected
C#public class BaseClass
{
// 私有的 protected 成员
private protected int Value = 100;
}
public class DerivedClass : BaseClass
{
public void ShowValue()
{
Console.WriteLine($"Value: {Value}");
}
}
internal class Program
{
static void Main(string[] args)
{
// 以下代码在同一程序集内有效
DerivedClass derived = new DerivedClass();
derived.ShowValue();
}
}
使用 private
修饰符来封装类的内部数据,防止外部直接访问。
C#public class Employee
{
private string name;
private int age;
public void SetName(string name)
{
this.name = name;
}
public string GetName()
{
return name;
}
// 其他方法...
}
使用 protected
修饰符允许派生类访问基类的成员。
C#public class Shape
{
protected int width;
protected int height;
}
public class Rectangle : Shape
{
public int GetArea()
{
return width * height;
}
}
使用 internal
限制类型和成员仅在当前程序集内可见。
C#// 在一个库项目中
internal class Utility
{
internal static void HelperMethod()
{
// 实现细节
}
}
访问修饰符在 C# 中起着至关重要的作用,它们控制着代码的可访问性,影响着类的设计和架构。正确使用访问修饰符可以:
在编写代码时,应根据实际需求,谨慎选择合适的访问修饰符,以编写出结构良好、可靠性高的程序。
建议:在实践中,多编写一些示例和练习,熟悉不同访问修饰符的作用和限制,这将有助于您成为一名更出色的 C# 开发者。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!