您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

如何使用C#实现单一职责原则?

2024/12/22 20:09:22发布31次查看
一个类应该只有一个改变的理由。
定义 - 在这种情况下,责任被认为是改变的一个原因。
该原则指出,如果我们有两个原因要更改某个类,则必须将功能拆分为两个类。每个类仅处理一项职责,如果将来我们需要进行一项更改,我们将在处理它的类中进行更改。当我们需要对具有更多职责的类进行更改时,该更改可能会影响与该类的其他职责相关的其他功能。
示例代码之前单一职责原则
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!"); } } }}
以上就是如何使用c#实现单一职责原则?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product