使用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);