gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:50:17 24 4
gpt4 key购买 nike

我有这个条件

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

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

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

最佳答案

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

助手

/* 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");
}

关于coding-style - 缩短/避免 if 语句中的级联空检查的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17657942/

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