相关疑难解决方法(0)

使用此(基于扩展方法)速记的可能陷阱

C#6更新

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)

我真正想要的是 …

c# extension-methods .net-3.5

15
推荐指数
5
解决办法
4566
查看次数

标签 统计

.net-3.5 ×1

c# ×1

extension-methods ×1