如何使用 C# 实现单一职责原则?
csharpserver side programmingprogramming更新于 2025/6/2 17:37:17
一个类应该只有一个需要修改的原因。
定义 − 在本文中,职责被视为修改的一个原因。
该原则指出,如果我们有两个修改某个类的原因,则必须将其功能拆分为两个类。每个类只处理一项职责,如果将来需要进行一项更改,我们将在处理该职责的类中进行更改。当我们需要对一个职责较多的类进行更改时,该更改可能会影响与该类其他职责相关的其他功能。
示例
遵循单一职责原则之前的代码
using System; using System.Net.Mail; namespace SolidPrinciples.Single.Responsibility.Principle.Before { class Program{ public static void SendInvite(string email,string firstName,string lastname){ if(String.IsNullOrWhiteSpace(firstName)|| String.IsNullOrWhiteSpace(lastname)){ throw new Exception("Name is not valid"); } if (!email.Contains("@") || !email.Contains(".")){ throw new Exception("Email is not Valid!"); } SmtpClient client = new SmtpClient(); client.Send(new MailMessage("Test@gmail.com", email) { Subject="Please Join the Party!"}) } } }
遵循单一职责原则编写代码
using System; using System.Net.Mail; namespace SolidPrinciples.Single.Responsibility.Principle.After{ internal class Program{ public static void SendInvite(string email, string firstName, string lastname){ UserNameService.Validate(firstName, lastname); EmailService.validate(email); SmtpClient client = new SmtpClient(); client.Send(new MailMessage("Test@gmail.com", email) { Subject = "Please Join the Party!" }); } } public static class UserNameService{ public static void Validate(string firstname, string lastName){ if (string.IsNullOrWhiteSpace(firstname) || string.IsNullOrWhiteSpace(lastName)){ throw new Exception("Name is not valid"); } } } public static class EmailService{ public static void validate(string email){ if (!email.Contains("@") || !email.Contains(".")){ throw new Exception("Email is not Valid!"); } } } }