加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:20:55 所属栏目:百科 来源:网络整理
导读:使用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我可以做到这一点
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读