如何将多个操作数应用于单个运算符?
一个例子:
代替
if (foo == "dog" || foo == "cat" || foo == "human")
Run Code Online (Sandbox Code Playgroud)
我可以有以下或类似的:
if (foo == ("dog" || "cat" || "human"));
Run Code Online (Sandbox Code Playgroud)
您的第一个版本已在一个表达式中包含多个运算符 听起来你想要将多个操作数("dog","cat","human")应用于单个操作符(==在本例中).
对于该特定示例,您可以使用:
// Note: could extract this array (or make it a set etc) and reuse the same
// collection each time we evaluate this.
if (new[] { "dog", "cat", "human" }.Contains(foo))
Run Code Online (Sandbox Code Playgroud)
但是对于所有运营商来说,没有通用的一刀切版本.
编辑:如评论中所述,上述内容的效果不如硬编码版本.
| 归档时间: |
|
| 查看次数: |
308 次 |
| 最近记录: |