使用 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#
我的意思是这部分
&& 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?)
(还有其他方法,但最终有一个空检查的快捷方式,称为空条件运算符).
也就是说,您的代码不能用语法优雅的陈述没有 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。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)