![](/img/trans.png)
[英]What's the fastest way to get an ObjectContext reference from an entity object?
[英]What is the fastest way to get a property from an object after checking that the object isn't null?
在检查对象不为null之后,从对象中获取属性的最快方法(就最大程度地减少代码语句而言)是什么?
string s = null;
if (null != myObject)
{
s = myObject.propertyName;
}
供参考:等待将来的C#6.0功能对可能的?.
进行空检查?.
句法:
string result = obj?.ToString();
现在:使用三元运算符 :
string result = obj != null ? obj.ToString() : null;
C#没有空值传播运算符(尽管已经讨论了几次)。 坦白地说,“更快”在这里不太可能成为一个因素,因为它通常会以相同(或足够相似)的IL结束,但是我倾向于使用:
string s = myObject == null ? null : myObject.PropertyName;
您所描述的情况只是操作员有用的一种情况。 替换这样的结构也很方便:
if (value != null)
{
return value;
}
else
{
return otherValue;
}
要么
return value != null ? value : otherValue;
与
return value ?? otherValue;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.