方法调用中的C#空检查链 [英] C# null check chain in method call

查看:49
本文介绍了方法调用中的C#空检查链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下面是方法调用链.

I suppose method call chain below.

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;
}

如果方法调用深度更深,则null检查将更多地重叠.有什么好的解决方案吗?

If method call depth get deeper, null checking will be more overlapped. Is there any good solution for this?

已修改

我更改了示例代码.将CreateA更改为构造函数无法解决我的问题.问题仅在于不必要的空检查链重叠.

I changed example code. It can't solve my problem that change CreateA to constructor. The problem is only unnecessary null check chaining overlapping.

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;
}

推荐答案

从C#6.0开始,您可以使用

Starting with C# 6.0 you can use Null-Conditional Operator, which lets you make null-checking implicitly:

var result = possiblyNull?.MethodThatCanReturnNull()?.SomeProperty;

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

This construct will produce a null result if any element in the chain produces null.

这篇关于方法调用中的C#空检查链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆