gpt4 book ai didi

c# - 现在有没有更简洁的方法来处理空检查?变量存在测试?

转载 作者:太空狗 更新时间:2023-10-29 22:56:37 25 4
gpt4 key购买 nike

我的代码目前看起来像这样:

if (control != null && control.Meta != null && control.State != null)
{
ConfigureMeta(control, control.Meta);
ConfigureColors(control, control.State);
}

现在是否有另一种更简洁的方法可以使用“?”进行空值检查已添加到最新版本的 C# 中?

最佳答案

您可以使用空条件运算符(C#6)来减少一次检查 - 添加(2015 年 7 月)

null-conditional operators

Tests the value of the left-hand operand for null before performing a member access (?.) or index (?[]) operation; returns null if the left-hand operand evaluates to null.

if (control?.Meta != null && control?.State != null)
{
}

如果你真的真的真的想让多重检查更容易并且你有可打印的字符OCD(你只是喜欢为了乐趣而编写方法)

您可以使用以下内容

public bool CheckAll(params object[] refs) => refs.All(x => x != null);

...

if (CheckAll(control?.Meta, control?.State))
{
}

关于c# - 现在有没有更简洁的方法来处理空检查?变量存在测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54879144/

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