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

如何在C#<6中模拟C#6空条件,第1张

概述使用C#6.0我可以做到这一点 var isEqual = x.Id == y.Id && x.UpdatedAt == y.UpdatedAt && x.Name == y.Name && x.RulesUrl == y.RulesUrl 使用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#<6中模拟C#6空条件全部内容,希望文章能够帮你解决如何在C#<6中模拟C#6空条件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1254893.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存