什么问号和点运算符?意思是在C#6.0? [英] What does question mark and dot operator ?. mean in C# 6.0?
问题描述
使用C#6.0中的VS2015 preVIEW我们有一个新的运营商,
,它可以这样使用:?
With C# 6.0 in the VS2015 preview we have a new operator, ?.
, which can be used like this:
public class A {
string PropertyOfA { get; set; }
}
...
var a = new A();
var foo = "bar";
if(a?.PropertyOfA != foo) {
//somecode
}
究竟是什么呢?
推荐答案
这是的 空条件的运营商。它主要是指:
It's the null conditional operator. It basically means:
评估第一个操作数;如果这是空,停止与空的结果,否则,评估第二个操作数(为第一个操作中的一员访问)
"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."
在您的例子中,问题是,如果 A
是空
,那么 A ?.PropertyOfA
将评估为空
而不是抛出一个异常 - 它就会比较一下空
参考与富
(使用字符串的 ==
过载),发现他们不是平等的,执行将进入身体如果
语句。
In your example, the point is that if a
is null
, then a?.PropertyOfA
will evaluate to null
rather than throwing an exception - it will then compare that null
reference with foo
(using string's ==
overload), find they're not equal and execution will go into the body of the if
statement.
在换句话说,它是这样的:
In other words, it's like this:
string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
...
}
...除了 A
只计算一次。
请注意,这可以改变前pression的类型,也。例如,考虑<一个href=\"https://msdn.microsoft.com/en-us/library/system.io.fileinfo.length\"><$c$c>FileInfo.Length$c$c>.这类型的属性长
,但如果你与空有条件的经营者使用它,你最终类型的前pression 长?
:
Note that this can change the type of the expression, too. For example, consider FileInfo.Length
. That's a property of type long
, but if you use it with the null conditional operator, you end up with an expression of type long?
:
FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null
这篇关于什么问号和点运算符?意思是在C#6.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!