C#中两个问号放在一起是什么意思? [英] What do two question marks together mean in C#?

查看:33
本文介绍了C#中两个问号放在一起是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

跑过这行代码:

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

这两个问号是什么意思,是某种三元运算符吗?很难在 Google 中查找.

What do the two question marks mean, is it some kind of ternary operator? It's hard to look up in Google.

推荐答案

它是空合并运算符,非常类似于三元 (immediate-if) 运算符.另请参阅 ??运营商 - MSDN.

It's the null coalescing operator, and quite like the ternary (immediate-if) operator. See also ?? Operator - MSDN.

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

扩展为:

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

进一步扩展为:

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."

请注意,您可以按顺序使用任意数量的这些.以下语句将第一个非空 Answer# 分配给 Answer(如果所有 Answers 都为空,则 Answer 为空):

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):

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

<小时>

另外值得一提的是,虽然上面的扩展在概念上是等价的,但每个表达式的结果只计算一次.例如,如果表达式是具有副作用的方法调用,则这一点很重要.(感谢@Joey 指出这一点.)


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.)

这篇关于C#中两个问号放在一起是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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