缩短/避免if语句中级联空检查的方法 [英] Way to shorten/avoid cascaded null checks in if-statements

查看:164
本文介绍了缩短/避免if语句中级联空检查的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个条件

if(Model.Bids != null && Model.Bids.Items != null && Model.Bids.Items.Count > 0)
{
  ...
}

问题是,我认为这是丑陋的。我可以写一个封装这个函数,但我想知道是否有其他的东西,将帮助我写一些像下面的重要比特,而不必做null检查。如果没有,那么这将是一个方便的语言扩展。

Problem is, I think this is ugly. I could write a function that encapsulates this but I wonder if there is something else that would help me write something like just the important bits below without having to do the null checks. If not then this would be a handy language extension.

if(Model.Bids.Items.Count > 0)
{
  ...
}


推荐答案

对于c#这两个选项实现你想要什么,但我不会把这在我的软件快速。
我也怀疑这更可读或更容易理解。还有另一个选项,但是需要你重构你的Model类链。如果您为出价 NullObject c>和 Item 中的类型,可以 if(Model.Bids.Items.Count> 0)所有类型都不会为null,但有一个处理Empty状态的实现(很像String.Empty)

For c# this two options achieve sort of what you want but I wouldn't put this in my software quickly. Also I doubt this gets more readable or better understandable. There is one other option but that requires you to refactor you Model class chain. If you implement a NullObject for the type in Bids and the type in Item you can do if(Model.Bids.Items.Count > 0) because all types will not be null but have an implementation that handles the Empty state (much like String.Empty)

helpers

helpers

/* take a func, wrap in a try/catch, invoke compare */
bool tc(Func<bool> comp )
{
    try
    {
        return comp.Invoke();
    }
    catch (Exception)
    {
        return false;
    }
}

/* helper for f */ 
T1 f1<T,T1>(T root, Func<T, T1> p1) where T:class 
{
    T1 res = default(T1);
    if (root != null)
    {
        res = p1.Invoke(root);
    }
    return res;
}

/*  take a chain of funcs and a comp if the last 
    in the chain is still not null call comp (expand if needed) */
bool f<T,T1,T2,TL>( T root, Func<T,T1> p1, Func<T1,T2> p2, Func<T2,TL> plast, 
        Func<TL, bool> comp) where T:class where T1:class where T2:class
{
    var allbutLast = f1(f1(root, p1), p2);
    return allbutLast != null && comp(plast.Invoke(allbutLast));
}


var m = new Model();
if (f(m, p => p.Bids, p => p.Items, p => p.Count, p => p > 0))
{
    Debug.WriteLine("f");
}
if (tc(() => m.Bids.Items.Count > 0))
{
    Debug.WriteLine("tc ");
}
if (m.Bids != null && m.Bids.Items != null && m.Bids.Items.Count > 0)
{
    Debug.WriteLine("plain");
}

这篇关于缩短/避免if语句中级联空检查的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆