缩短/避免 if 语句中级联空检查的方法

2023-12-08

我有这个条件

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

问题是,我认为这很丑陋。我可以编写一个封装此函数的函数,但我想知道是否还有其他东西可以帮助我编写类似下面的重要位的内容,而无需进行空检查。如果没有的话,这将是一个方便的语言扩展。

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

对于 C#,这两个选项可以实现您想要的效果,但我不会很快将其放入我的软件中。 我也怀疑这会变得更具可读性或更好理解性。还有另一种选择,但这需要您重构模型类链。如果你实施一个空对象对于输入Bids并输入Item你可以做if(Model.Bids.Items.Count > 0)因为所有类型都不会为 null,但都有一个处理 Empty 状态的实现(很像 String.Empty)

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));
}

Usage

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");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

缩短/避免 if 语句中级联空检查的方法 的相关文章