Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

c# - C#中两个问号共同意味着什么?(What do two question marks together mean in C#?)

Ran across this line of code:

(跨越这行代码:)

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

What do the two question marks mean, is it some kind of ternary operator?

(这两个问号意味着什么,是某种三元运算符?)

It's hard to look up in Google.

(谷歌很难找到。)

  ask by Edward Tanguay translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's the null coalescing operator, and quite like the ternary (immediate-if) operator.

(它是空合并运算符,非常类似于三元(立即if)运算符。)

See also ??

(另见??)

Operator - MSDN .

(运营商 - MSDN 。)

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

expands to:

(扩展为:)

FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();

which further expands to:

(进一步扩展到:)

if(formsAuth != null)
    FormsAuth = formsAuth;
else
    FormsAuth = new FormsAuthenticationWrapper();

In English, it means "If whatever is to the left is not null, use that, otherwise use what's to the right."

(在英语中,它表示“如果左边的任何内容不为空,请使用它,否则使用右边的内容。”)

Note that you can use any number of these in sequence.

(请注意,您可以按顺序使用任意数量的这些。)

The following statement will assign the first non-null Answer# to Answer (if all Answers are null then the Answer is null):

(以下语句将第一个非空的Answer#分配给Answer (如果所有Answers都为null,则Answer为null):)

string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;

Also it's worth mentioning while the expansion above is conceptually equivalent, the result of each expression is only evaluated once.

(值得一提的是,虽然上面的扩展在概念上是等价的,但每个表达式的结果只评估一次。)

This is important if for example an expression is a method call with side effects.

(例如,如果表达式是带副作用的方法调用,则这很重要。)

(Credit to @Joey for pointing this out.)

((感谢@Joey指出这一点。))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...