方法调用中的C#null检查链

seu*_*Son 3 c# null-check

我想下面的方法调用链.

void DoSomething()
{
    ObjectA a = CreateA();
    if (a != null)
    {
        a.Foo();
    }
}

ObjectA CreateA()
{
    ObjectB b = CreateB();
    if (b != null)
    {    
        ObjectA a = b.ToA();
        return a;
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

如果方法调用深度变深,则空检查将更加重叠.对此有什么好的解决方案吗?

改性

我改变了示例代码.它无法解决我将CreateA更改为构造函数的问题.问题是只有不必要的空检查链接重叠.

void SetImage()
{
    UISprite image = GetSprite();
    if (image  != null)
    {
        image.spriteName = "hat";
    }
}

UISprite GetSprite()
{
    UISprite image = GetComponent<UISprite>();
    if (image  != null)
    {   
        image.width = 100;
        image.height = 100;
        return image;
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 8

从C#6.0开始,您可以使用Null-Conditional Operator,它允许您隐式进行空检查:

var result = possiblyNull?.MethodThatCanReturnNull()?.SomeProperty;
Run Code Online (Sandbox Code Playgroud)

null如果链中的任何元素产生,则此构造将产生结果null.