方法调用中的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;
}
答
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
.