如何在C#<6中模拟C#6空条件

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

整个扩展方法将用于获取值类型属性值或其认值.您可能扩展方法类也可能不会扩展,也支持获取引用类型值或为null.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...