c# - 优化 if 和 foreach 的 null 检查

标签 c# asp.net .net c#-4.0

有办法优化此代码以进行空检查吗?

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/

相关文章:

c# - 在离线 C# webforms 应用程序中使用 OpenStreetMap 数据

asp.net - 从 ASP .Net Web 服务访问 MSMQ 时出现权限错误

c# - 如何在运行时更改 CurrentCulture?

c# - 反序列化 XML 文件而不将其全部加载到内存中

c# - Entity Framework 6 中存储过程的执行是否需要调用 SaveChanges?

javascript - 处理 AJAX 返回上的 MVC 验证错误消息

c# - 在 C# 中将 Doc 自动化为 PDF

asp.net - 将 packageReference 和 packages.config 混合在一个解决方案中?

c# - 使用线程显示表单

c# - WatiN NativeElement.GetElementBounds() - 测量单位是什么?