C#吗?操作员短路? [英] Does c# ?? operator short circuit?

查看:100
本文介绍了C#吗?操作员短路?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中使用??运算符时,如果要测试的值不为null会短路吗?

When using the ?? operator in C#, does it short circuit if the value being tested is not null?

示例:

string test = null;
string test2 = test ?? "Default";

string test3 = test2 ?? test.ToLower();

test3行成功还是抛出空引用异常?

Does the test3 line succeed or throw a null reference exception?

以另一种方式表达问题的方式是:右手表达??吗?如果左手不为空,运算符会得到评估吗?

So another way to phrase the question: Will the right hand expression of the ?? operator get evaluated if the left hand is not null?

推荐答案

是的,它在

Yes, it says so in the C# Language Specification (highlighting by me):

a ?? b形式的空合并表达式要求a为可空类型或引用类型.如果a不为空,则a ?? b的结果为a;否则,结果为b. 仅当a为空时,该操作才会评估b.

A null coalescing expression of the form a ?? b requires a to be of a nullable type or reference type. If a is non-null, the result of a ?? b is a; otherwise, the result is b. The operation evaluates b only if a is null.

这篇关于C#吗?操作员短路?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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