成员访问中的问号在C#中意味着什么?

时间:2014-10-01 13:28:35

标签: c# null operators

有人可以向我解释以下代码中成员访问中的问号是什么意思吗?

它是标准C#的一部分吗?尝试在Xamarin Studio中编译此文件时出现解析错误。

this.AnalyzerLoadFailed?.Invoke(this, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, null, null));

AnalyzerFileReference.cs第195行

2 个答案:

答案 0 :(得分:15)

C#6 中引入了Null Propagation operator,只有当对象this.AnalyzerLoadFailed不为空时才会调用该方法:

this.AnalyzerLoadFailed?.Invoke(this, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, null, null));

等于:

if( this.AnalyzerLoadFailed != null)
    this.AnalyzerLoadFailed.Invoke(this, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, null, null));

请参阅C# 6.0 – Null Propagation Operator,您也可以看到here

我也曾在c#6 here

中写过这篇即将发布的专题文章

答案 1 :(得分:6)

在C#版本6中,它将是

的简写
if (this.AnalyzerLoadFailed != null)
    this.AnalyzerLoadFailed.Invoke(this, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, null, null));