C# 中令人困惑的简写运算符 (?) 语句

问题描述 投票:0回答:1

我是一名 C++/CLI 程序员,一直在尝试为我的程序实现一个非常轻量级的 Json 库。我现在有一个很好的工作代码,但问题是它比一些 JSON 解析器(例如 Newtonsoft.JSON)慢大约 5 倍。因此,我尝试研究它的代码,看看为什么它这么快,并遇到了这个我无法理解的语句。我在谷歌和这里进行了很多研究,但似乎没有什么能够帮助我完全理解。考虑以下陈述。

JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null);

这里,JsonPosition是一个具有一些属性的类。它只有一个将 JsonContainerType (枚举类)值作为参数的构造函数。 _currentPosition 的类型为 JsonPosition_currentState 是一个变量,保存名为 State 的枚举类的值。

对我来说,它翻译成以下内容。

JsonPosition^ currentPosition = ((_currentState != State::ArrayStart && _currentState != State::ConstructorStart && _currentState != State::ObjectStart) ? something : nullptr);

我无法理解 new JsonPosition?(_currentPosition) 部分,因为 (a) 在类名和左圆括号之间放置问号,并且 (b) JsonPosition 没有采用以下参数的构造函数输入 JsonPosition。

c++-cli
1个回答
0
投票

JsonPosition^ currentPosition = ((_currentState != State::ArrayStart && _currentState != State::ConstructorStart && _currentState != State::ObjectStart) ? gcnew JsonPosition(_currentPosition) : nullptr); 我想这应该是答案。 Json 位置?是一个可为空的类型。这意味着 currentPosition 可以指定为 null,条件运算符检查 _currentState 是否不等于 State.ArrayStart、State.ConstructorStart 和 State.ObjectStart。如果条件为真,则执行 : (new JsonPosition?(_currentPosition)) 之前的表达式,否则执行 : (null) 之后的表达式。

© www.soinside.com 2019 - 2024. All rights reserved.