c#6中?和.运算符是什么意思

What does question mark and dot operator ?. mean in C# 6.0?

在VS2015预览版中有了C 6.0,我们有了一个新的运营商,?.,可以这样使用:

1
2
3
4
5
6
7
8
9
10
11
public class A {
   string PropertyOfA { get; set; }
}

...

var a = new A();
var foo ="bar";
if(a?.PropertyOfA != foo) {
   //somecode
}

它到底是做什么的?


这是"零条件的经营者。它基本上意味着:P></

"the第一操作数评价;如果是空,空切,用result of。其他评价,第二操作数(as of the first成员访问操作符)。"P></

在你的example,the Point is that if ais to null,然后将评价a?.PropertyOfAnullRather比将安恩会出现例外,那么,nullfoo(S与参考使用string' ==overload),发现他们不平等和Will Go into the执行体是ifof the清单。P></

在其他的话,它是这样的:P></

1
2
3
4
5
string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
    ...
}

……除了athat is only evaluated盎司。P></

that this can change the笔记type of the expression,太。FileInfo.Lengthfor example,考虑。这是在longproperty of type,but with the null如果你使用它的条件的经营者,你端上安有:long?expression of typeP></

1
2
FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null


它可以非常有用,当flattening层和/或映射到对象。:instead ofP></

1
2
3
4
5
6
7
8
9
10
11
if (Model.Model2 == null
  || Model.Model2.Model3 == null
  || Model.Model2.Model3.Model4 == null
  || Model.Model2.Model3.Model4.Name == null)
{
  mapped.Name ="N/A"
}
else
{
  mapped.Name = Model.Model2.Model3.Model4.Name;
}

恩好(can be same as above逻辑类)P></

1
mapped.Name = Model.Model2?.Model3?.Model4?.Name ??"N/A";

dotnetfiddle .NET工作实例。P></

(the?coalescing社零?或是不同的比?零条件或经营者)。P></

它也可以使用端配置好了学院与经营者的行动。instead ofP></

1
2
3
4
5
6
Action<TValue> myAction = null;

if (myAction != null)
{
  myAction(TValue);
}

恩:simplified can be toP></

1
myAction?.Invoke(TValue);

dotnetfiddle实例:P></

利用系统;P></

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Program
{
  public static void Main()
  {
    Action<string> consoleWrite = null;

    consoleWrite?.Invoke("Test 1");

    consoleWrite = (s) => Console.WriteLine(s);

    consoleWrite?.Invoke("Test 2");
  }
}

结果:P></

Test 2


relatively this is to which makes #纽约C to the更容易激起美国呼叫函数与零或非零to the method chaining值。P></

旧的方式是:the same thing was toP></

1
2
3
var functionCaller = this.member;
if (functionCaller!= null)
    functionCaller.someFunction(var someParam);

EN has been现在只是easier与自制的多:P></

1
member?.someFunction(var someParam);

你读的recommend强:恩。P></

docs.microsoft.com HTTPS:/ / / / /销售额/ Dotnet CSharp语言参考/代理商/空条件算子P></