详解)
封装Encapsulation是面向对象编程OOP的四大特性之一另外三个是继承Inheritance多态Polymorphism抽象Abstraction封装的核心思想隐藏对象内部实现细节只向外暴露必要的功能接口。简单理解数据字段放在类内部外部不能随意修改通过属性、方法控制访问一、为什么需要封装假设有一个学生类class Student { public int Age; }使用Student stu new Student(); stu.Age -100;虽然语法正确但年龄不可能是负数。为了防止非法数据需要封装。二、使用 private 封装字段class Student { private int age; public void SetAge(int value) { if (value 0) { age value; } } public int GetAge() { return age; } }调用Student stu new Student(); stu.SetAge(18); Console.WriteLine(stu.GetAge());结果18三、访问修饰符C# 使用访问修饰符实现封装。修饰符访问范围public任何地方private当前类内部protected当前类和子类internal当前程序集protected internal当前程序集或子类示例class Person { public string Name; private int age; }外部Person p new Person(); p.Name Tom; //可以 p.age 18; //错误四、属性Property封装实际开发最常用。传统写法class Student { private int age; public int Age { get { return age; } set { if (value 0) { age value; } } } }使用Student stu new Student(); stu.Age 20; Console.WriteLine(stu.Age);输出20五、get 和 setget读取属性值Console.WriteLine(stu.Age);执行get { return age; }set赋值属性值stu.Age 18;执行set { age value; }其中value表示赋给属性的值。例如stu.Age 18;那么value 18六、自动属性如果不需要验证逻辑class Student { public int Age { get; set; } }编译器自动生成私有字段。使用Student stu new Student(); stu.Age 18;七、只读属性方式1public string Name { get; }只能读取public class Student { public string Name { get; } public Student(string name) { Name name; } }方式2public string Name { get; private set; }外部只能读Student stu new Student(); Console.WriteLine(stu.Name); // stu.Name Tom; 错误类内部可修改Name Jerry;八、封装业务逻辑例如银行卡余额class BankAccount { private decimal balance; public decimal Balance { get { return balance; } } public void Deposit(decimal money) { if (money 0) { balance money; } } public bool Withdraw(decimal money) { if (money balance) { balance - money; return true; } return false; } }使用BankAccount account new BankAccount(); account.Deposit(1000); account.Withdraw(300); Console.WriteLine(account.Balance);结果700优点防止余额被随意修改保证业务规则正确数据更安全九、封装与字段的区别❌ 不推荐public string Name;任何人都能直接修改obj.Name ; obj.Name null;✅ 推荐private string name; public string Name { get { return name; } set { if (!string.IsNullOrEmpty(value)) { name value; } } }十、完整案例using System; class Employee { private string name; private decimal salary; public string Name { get { return name; } set { if (!string.IsNullOrWhiteSpace(value)) { name value; } } } public decimal Salary { get { return salary; } set { if (value 0) { salary value; } } } public void ShowInfo() { Console.WriteLine($姓名{Name}); Console.WriteLine($工资{Salary}); } } class Program { static void Main() { Employee emp new Employee(); emp.Name 张三; emp.Salary 8000; emp.ShowInfo(); } }输出姓名张三 工资8000实际开发最佳实践现代 C#C# 8中推荐public class User { public string UserName { get; set; } public int Age { get; private set; } public User(string userName, int age) { UserName userName; if (age 0) throw new ArgumentException(年龄不能小于0); Age age; } }原则字段尽量使用private对外优先暴露属性Property在set中做数据验证重要业务数据通过方法操作不直接开放set保持“高内聚、低耦合”隐藏实现细节一句话总结C# 封装 private 字段 Property 属性 方法控制访问目的是保护数据安全、隐藏实现细节、保证对象状态合法。