简体   繁体   English

C#条件运算符-这怎么了?

[英]C# Conditional Operator - How is this Wrong?

I cannot figure out what I'm doing wrong for the life of me. 我无法弄清楚自己一生中做错了什么。 I've been using ?: throughout the life of my project but all of a sudden I keep being told "Only assignment, call, increment, decrement and new object expressions can be used" yet if I copy and paste the exact same thing into another file.. I get no error like that. 我一直在使用?:在我的项目的整个生命周期中,但突然我一直被告知“只能使用赋值,调用,递增,递减和新对象表达式”,但是如果我将完全相同的内容复制并粘贴到另一个文件..我没有得到这样的错误。

true ? 是吗 "1" : "1"; “ 1”:“ 1”; should be the most basic statement that works, correct? 应该是最有效的基本陈述,对吗? I mean it already does elsewhere so what could I be not understanding? 我的意思是说它已经在其他地方做了,所以我可能不明白什么?

条件陈述

When you say you are using conditional operator elsewhere & it is working fine perhaps you are using it in a way different than the screen capture you have shared. 当您说您在其他地方使用条件运算符并且运行良好时,也许您在使用它的方式与您共享的屏幕截图不同。 I say this because C# won't allow you to do it in the way you mentioned: ie 我说这是因为C#不允许您按照您提到的方式进行操作:即

true ? "1" : "1";

Think of it this way: Conditional operator is in essence an if-else. 这样想:条件运算符本质上是if-else。

if (true)
    "1"; //does not make sense, it appears to be string but the compiler needs to know what this is exactly
else
    "1"; //same comment as above

To summarize you need to assign that string "1" to a variable & then things would work fine. 总结一下,您需要将字符串“ 1”分配给变量,然后一切正常。

string str = true ? "1" : "1";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM