如何更简洁地实现多变量空值检查与属性赋值?
优化LDAP属性赋值的简洁实现方案
你的这段代码存在冗余的嵌套判断逻辑,其实每个属性的赋值逻辑完全独立,没必要做外层的整体空值判断,下面提供几种更简洁的优化方案:
方案一:使用空合并运算符简化赋值
直接利用C#的?.空条件运算符和??空合并运算符,一行完成每个属性的空值判断与赋值,彻底消除所有冗余的if分支:
try { var user = new ADUser(); nextEntry = ldapSearch.Next(); var attName = nextEntry.getAttribute("name"); var attMail = nextEntry.getAttribute("mail"); var attTelephone = nextEntry.getAttribute("telephoneNumber"); // 一行完成空值判断与赋值,为空则设为"" user.name = attName?.StringValue ?? ""; user.mail = attMail?.StringValue ?? ""; user.telephone = attTelephone?.StringValue ?? ""; model.ADUserList.Add(user); } catch { continue; }
方案二:封装扩展方法复用逻辑
如果需要在多处处理LDAP属性的空值,可以封装一个扩展方法,把空值判断的逻辑抽离出来,让代码更具可读性和复用性:
首先定义扩展方法(需确保所在类为静态类):
public static class LdapAttributeExtensions { public static string GetStringValueOrDefault(this LdapAttribute attribute) { return attribute?.StringValue ?? ""; } }
然后在业务代码中直接调用:
try { var user = new ADUser(); nextEntry = ldapSearch.Next(); var attName = nextEntry.getAttribute("name"); var attMail = nextEntry.getAttribute("mail"); var attTelephone = nextEntry.getAttribute("telephoneNumber"); user.name = attName.GetStringValueOrDefault(); user.mail = attMail.GetStringValueOrDefault(); user.telephone = attTelephone.GetStringValueOrDefault(); model.ADUserList.Add(user); } catch { continue; }
这两种方案都能大幅简化代码,去掉冗余的嵌套判断,逻辑更清晰易维护。
内容的提问来源于stack exchange,提问作者bezzgi
相关产品推荐
相关产品推荐

