我想知道是否有人可以为此代码提出缩短版本:
MyObject theObject = ObjectCollection.GrabAnObject();
if (theObject == null) return String.Empty;
else return theObject.myProperty;
MyObject theObject = ObjectCollection.GrabAnObject();
if (theObject == null) return String.Empty;
else return theObject.myProperty;
谢谢!
答案 0 :(得分:8)
MyObject theObject = ObjectCollection.GrabAnObject();
return theObject == null ? String.Empty : theObject.myProperty;
答案 1 :(得分:4)
在c#3.0(框架3.5)中,您可以写:
return (ObjectCollection.GrabAnObject() ?? new MyObject(){ myProperty = ""} ).myProperty;
但我会写一些更具可读性的内容,如:
返回新的MyObject(ObjectCollection.GrabAnObject())
并在构造函数
中设置属性编辑: 我的记忆让我开玩笑: ??不是c#3.0功能,而是2.0版;)
答案 2 :(得分:2)
该代码没问题,但我建议使用以下内容来提高可读性(and I'm not the only one)。
MyObject theObject = ObjectCollection.GrabAnObject();
if (theObject != null)
return theObject.myProperty;
return string.Empty;
答案 3 :(得分:2)
var theObject = ObjectCollection.GrabAnObject();
return theObject != null ? theObject.myProperty : String.Empty;
// if you want an String.Empty always to be returned, also when the property is null
return theObject != null ? theObject.myProperty ?? String.Empty : String.Empty;
答案 4 :(得分:1)
使用?:
运算符:
MyObject theObject = ObjectCollection.GrabAnObject();
return (theObject == null) ? String.Empty : theObject.myProperty;
答案 5 :(得分:1)
当然,你可以使用?运营商。
MyObject theObject = ObjectCollection.GrabAnObject();
return (theObject == null) ? String.Empty : theObject.myProperty;
我不相信你可以在不调用ObjectCollection.GrabAnObject()两次的情况下在一行上获得这个。