面向对象 就是把数据与操作方式放在一起,仅保留部分通道供外界调用。 直接看例子🌰 class RemoteControl { // 数据为私有,存在类里面 private int _volume = 10; // 操作公开,是操作数据的唯一入口 public void IncreaseVolume() { _volume++; Console.WriteLine($"音量:{_volume}"); } public void DecreaseVolume() { if (_volume > 0) // 可以加保护逻辑 { _volume--; Console.WriteLine($"音量:{_volume}"); } } } // 使用时:数据和操作是一个整体 var remote = new RemoteControl(); remote.IncreaseVolume(); // 音量:11 这就是面向对象 这时候可能有人要问:为什么要这样写,和面向过程比有什么优势? 首先就是封装:对数据起到很好的保护,避免外界干扰 看例子 class BankAccount { private decimal _balance; // 余额绝对不让外面直接改 public void Deposit(decimal amount) { if (amount <= 0) throw new Exception("存钱金额必须大于0"); _balance += amount; // 有校验的保护 } public decimal GetBalance() { return _balance; // 只读 } } 面向过程的数据字段直接暴露在外,随便一个方法或是什么都能改,数据不安全 这是面向过程 // 数据是数据,直接放在外面 int volume = 10; // 操作是操作,分开的 void IncreaseVolume() { volume++; Console.WriteLine($"音量:{volume}"); } void DecreaseVolume() { volume--; Console.WriteLine($"音量:{volume}"); } // 使用时:数据和方法没有绑定 IncreaseVolume(); // 音量:11 IncreaseVolume(); // 音量:12 无法保证数据会不会出现负数或者大到离谱 其次是继承 // 普通遥控器 class RemoteControl { public void PowerOn() { Console.WriteLine("开机"); } } // 智能遥控器:继承普通遥控器,再加新功能 class SmartRemote : RemoteControl { public void VoiceControl() { Console.WriteLine("语音控制"); } } // 使用 var smart = new SmartRemote(); smart.PowerOn(); // 继承来的 smart.VoiceControl(); // 自己的 可以不重新PowerOn,直接拿过来用,再加新功能 最后是多态 // 定义一个接口:所有设备都能开机 interface IDevice { void TurnOn(); } class TV : IDevice { public void TurnOn() => Console.WriteLine("电视屏幕亮了"); } class Speaker : IDevice { public void TurnOn() => Console.WriteLine("音箱播放开机音效"); } // 遥控器面对任何设备,统一操作 class RemoteControl { public void PressPower(IDevice device) { device.TurnOn(); // 同一个动作,不同设备不同表现 } } var remote = new RemoteControl(); remote.PressPower(new TV()); // 电视屏幕亮了 remote.PressPower(new Speaker()); // 音箱播放开机音效 此时,可以看出来,依赖注入就是建立在面向对象的‘’多态‘’基础上的
面向对象:为何要面向对象
以下为完整正文内容。
正文
搜索结果
请输入关键词开始搜索。