[英]What is the fastest way to get a property from an object after checking that the object isn't null?
What is the fastest way (in terms of minimizing the amount of code statements) 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;
}
For reference: Wait for future C# 6.0 feature for null checking with possible ?.
供参考:等待将来的C#6.0功能对可能的
?.
进行空检查?.
syntax: 句法:
string result = obj?.ToString();
For now: Use ternary operator : 现在:使用三元运算符 :
string result = obj != null ? obj.ToString() : null;
C# does not have a null-propagating operator (although it has been discussed a few times). C#没有空值传播运算符(尽管已经讨论了几次)。 Frankly, "faster" is not likely to be a factor here, as it will typically end up in the same (or similar enough) IL, but I tend to use:
坦白地说,“更快”在这里不太可能成为一个因素,因为它通常会以相同(或足够相似)的IL结束,但是我倾向于使用:
string s = myObject == null ? null : myObject.PropertyName;
the situation you describe is only one scenario where the operator is useful. 您所描述的情况只是操作员有用的一种情况。 It's also handy to replace constructs like this:
替换这样的结构也很方便:
if (value != null)
{
return value;
}
else
{
return otherValue;
}
Or 要么
return value != null ? value : otherValue;
with 与
return value ?? otherValue;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.