gpt4 book ai didi

c# - 简化条件if语句c#

转载 作者:行者123 更新时间:2023-11-30 15:53:04 25 4
gpt4 key购买 nike

我有一个 if 语句,变得有点麻烦。我想知道是否有更好的方法来处理多个类似的 if 语句,例如组合成一个或使用不同的条件语句,例如 while 或 do 循环。任何建议表示赞赏。

if (options.OpenCloseOverridesOptions != null && !options.OpenCloseOverridesOptions.AreEqual(OpenCloseOverridesOptions))
return false;

if (options.DeliveryOpenCloseOverridesOptions != null && !options.DeliveryOpenCloseOverridesOptions.AreEqual(DeliveryOpenCloseOverridesOptions))
return false;

if (options.PickupOpenCloseOverridesOptions != null && !options.PickupOpenCloseOverridesOptions.AreEqual(PickupOpenCloseOverridesOptions))
return false;

if (options.PickupServiceWindowOverridesOptions != null && !options.PickupServiceWindowOverridesOptions.AreEqual(PickupServiceWindowOverridesOptions))
return false;

if (options.DeliveryServiceWindowOverridesOptions != null && !options.DeliveryServiceWindowOverridesOptions.AreEqual(DeliveryServiceWindowOverridesOptions))
return false;

if (options.ServiceWindowOverridesOptions != null && !options.ServiceWindowOverridesOptions.AreEqual(ServiceWindowOverridesOptions))
return false;

if (options.LineItemsOptions != null && !options.LineItemsOptions.AreEqual(LineItemsOptions))
return false;

简而言之,我基本上是在检查一个对象是否为 null,如果不为 null,则使用扩展方法来确定一个相似的对象是否相等。 (我没有覆盖 isEquals 和 getHashCode )。如果对象为 null,我无法调用 areEquals 扩展方法,因此有必要进行检查。

最佳答案

如果要返回bool可以直接返回条件

我们可以使用另一个技能 ( De Morgan's laws ) 让!放入语句中,将所有逻辑颠倒过来,让代码更清晰。

return  
(options.OpenCloseOverridesOptions == null || options.OpenCloseOverridesOptions.AreEqual(OpenCloseOverridesOptions)) &&
(options.DeliveryOpenCloseOverridesOptions == null || options.DeliveryOpenCloseOverridesOptions.AreEqual(DeliveryOpenCloseOverridesOptions)) &&
(options.PickupOpenCloseOverridesOptions == null || options.PickupOpenCloseOverridesOptions.AreEqual(PickupOpenCloseOverridesOptions))&&
(options.PickupServiceWindowOverridesOptions == null || options.PickupServiceWindowOverridesOptions.AreEqual(PickupServiceWindowOverridesOptions) &&
(options.DeliveryServiceWindowOverridesOptions == null || options.DeliveryServiceWindowOverridesOptions.AreEqual(DeliveryServiceWindowOverridesOptions)&&
(options.ServiceWindowOverridesOptions == null || options.ServiceWindowOverridesOptions.AreEqual(ServiceWindowOverridesOptions)&&
(options.LineItemsOptions == null || options.LineItemsOptions.AreEqual(LineItemsOptions)

关于c# - 简化条件if语句c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53209212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com