使用C#6.0我可以做到这一点
var isEqual = x.Id == y.Id && x.UpdatedAt == y.UpdatedAt && x.Name == y.Name && x.RulesUrl == y.RulesUrl && x.OngoingChallenges?.Count == y.OngoingChallenges?.Count && x.MembershipIds?.Count == y.MembershipIds?.Count;
有没有什么好的解决方案来做到这一点与C# 6.0?
我的意思是这部分
&& x.OngoingChallenges?.Count == y.OngoingChallenges?.Count && x.MembershipIds?.Count == y.MembershipIds?.Count;
因为在旧的项目中,我们没有使用C#6.0的可能性.如何有效地编写isEqual?
解决方法
x.OnGoingChallenges?.Count等价于x.OnGoingChallenges!= null? x.OnGoingChallenges.Count:default(int?)(还有其他的方法,但是在一天结束时是一个调用null条件运算符的空检查的快捷方式).
也就是说,您的代码不能用没有C#6的合成优雅语句重写,但您可以使用扩展方法来模拟此新的C#6功能…
public static class StructExtensions { // Check that TProperty is nullable for the return value (this is how C#6's // null-conditional operator works with value types public static TProperty? GetorDefault<TObject,TProperty>(this TObject someObject,Func<TObject,TProperty> propertySelectionFunc) where TObject : class where TProperty : struct { Contract.Requires(propertySelectionFunc != null); return someObject == null ? default(TProperty?) : propertySelectionFunc(someObject); } }
现在你在C#5中的代码如下所示:
var isEqual = x.Id == y.Id && x.UpdatedAt == y.UpdatedAt && x.Name == y.Name && x.RulesUrl == y.RulesUrl && x.OngoingChallenges.GetorDefault(c => c.Count) == y.OngoingChallenges.GetorDefault(c => c.Count) && x.MembershipIds.GetorDefault(m => m.Count) == x.MembershipIds.GetorDefault(m => m.Count);
原文地址:https://www.jb51.cc/c/111732.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。