【发布时间】:2017-08-25 04:29:29
【问题描述】:
我想下面是方法调用链。
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;
}
如果方法调用深度越深,空值检查就会越重叠。 有什么好的解决办法吗?
修改
我更改了示例代码。将 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;
}
【问题讨论】:
-
您可能想查看 C# 6 空条件运算符 msdn.microsoft.com/en-us/library/dn986595.aspx
-
@Nelson C# 3.0 我认为。(使用 Unity 5.4)
标签: c# null-check