C#中两个问号放在一起是什么意思?

编程入门 行业动态 更新时间:2024-10-18 08:34:05
本文介绍了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#中两个问号放在一起是什么意思?

本文发布于:2023-11-28 07:07:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641410.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:问号   放在一起   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!