什么问号和点运算符?意思是在C#6.0? [英] What does question mark and dot operator ?. mean in C# 6.0?

查看:599
本文介绍了什么问号和点运算符?意思是在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.这类型的属性,但如果你与空有条件的经营者使用它,你最终类型的前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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆