C#6更新
// C#1-5
propertyValue1 = myObject != null ? myObject.StringProperty : null;
// C#6
propertyValue1 = myObject?.StringProperty;
Run Code Online (Sandbox Code Playgroud)
下面的问题仍适用于旧版本,但如果使用new ?.运算符开发新应用程序则更好.
原始问题:
我经常想要访问可能为null的对象的属性:
string propertyValue1 = null;
if( myObject1 != null )
propertyValue1 = myObject1.StringProperty;
int propertyValue2 = 0;
if( myObject2 != null )
propertyValue2 = myObject2.IntProperty;
Run Code Online (Sandbox Code Playgroud)
等等...
我经常使用它,因此我有一个代码片段.
如果符合以下条件,您可以在某种程度上缩短此内容:
propertyValue1 = myObject != null ? myObject.StringProperty : null;
Run Code Online (Sandbox Code Playgroud)
然而,这有点笨拙,特别是如果设置大量属性或多个级别可以为null,例如:
propertyValue1 = myObject != null ?
(myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null;
Run Code Online (Sandbox Code Playgroud)
我真正想要的是 …