如何在C#<中模拟C#6空条件6 [英] How to emulate C# 6 null-conditional in C# < 6
问题描述
使用C#6.0,我可以做到
With C# 6.0 I can do this
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?
Is there any nice solution to do this with C# < 6.0?
我的意思是这部分
&& x.OngoingChallenges?.Count == y.OngoingChallenges?.Count
&& x.MembershipIds?.Count == y.MembershipIds?.Count;
由于在旧项目中,我们无法使用C#6.0.如何有效地编写 isEqual
?
Because in old projects we do not have possibility to use C# 6.0. How to write isEqual
efficiently?
推荐答案
x.OnGoingChallenges?.Count
等同于 x.OnGoingChallenges!= null?x.OnGoingChallenges.Count:default(int?)
(还有其他方法,但是到了最后,空检查的快捷方式称为 null-conditional operator ).
x.OnGoingChallenges?.Count
is equivalent to x.OnGoingChallenges != null ? x.OnGoingChallenges.Count : default(int?)
(there're other approaches, but at the end of the day is a shortcut to null checking called null-conditional operator).
也就是说,如果没有C#6,就无法使用优雅的语句重写代码,但是您可以使用扩展方法来模仿此新的C#6功能...
That is, your code can't be rewritten with a syntatically elegant statement without C# 6, but you can emulate this new C# 6 feature using extension methods...
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中的代码将如下所示:
And now your code in C#5 would look as follows:
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.
The whole extension method would work for getting a value-typed property value or its default value. You might or might not extend the extension method class to also support getting a reference type value or null.
这篇关于如何在C#<中模拟C#6空条件6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!