有办法优化此代码以进行空检查吗?
if (objA != null && objA .Length > 0)
{
foreach (var child in objA )
{
if (child.Any != null)
{
foreach (var a in child.Any)
{
if (a.Name.ToLower() == "code")
{
//some code
}
}
}
}
}
最佳答案
我认为您想要使用 C# 6 null 条件 ?
运算符。这是一些伪代码:
for (int i = 0; i < objA?.Length; i++)
{
ExecuteCode(objA[i]?.Any);
}
...
static void ExecuteCode(YourTypeHere[] children)
{
for (int i = 0; i < children?.Length; i++)
{
if (children[i]?.Name?.ToLower() == "code")
{
//some code
}
}
}
使用 for 循环比 foreach 更快:In .NET, which loop runs faster, 'for' or 'foreach'? 。两个循环都比 Linq 稍快。
关于c# - 优化 if 和 foreach 的 null 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50093708/