简体   繁体   English

使用C#条件运算符的编译器错误

[英]Compiler error using C# conditional operator

I can't seem to find what I need on google, and bet I'll get quick answer here. 我似乎无法在Google上找到所需的东西,并且打赌我会在这里得到快速解答。

    String str;
    bool b = true;
    b ? str="true" : str="false";

    Console.Out.WriteLine(str);

that ? 那? : syntax looks correct to me. :语法对我来说似乎正确。 I'm getting compiler error though. 我遇到编译器错误。

Program.cs(13,28): Program.cs(13,28):
error CS1002: ; 错误CS1002 :; expected 预期
Program.cs(13,28): Program.cs(13,28):
error CS1525: Invalid expression term ':' 错误CS1525:无效的表达式术语':'
Program.cs(13,30): Program.cs(13,30):
error CS1002: ; 错误CS1002 :; expected 预期

Not sure about the csharp syntax, but that builds in cpp. 不确定csharp语法,但这内置于cpp中。 Please help! 请帮忙! thanks! 谢谢!

UPDATE: About 10 of you give the correct answer LOL, so I'll just award to the first person who submitted it. 更新:你们中大约有10人给出了正确的答案,哈哈,所以我将奖励授予它的第一个人。

interesting Syntax, and I think I actually like it better than c++ syntax. 有趣的语法,我想我实际上比c ++语法更喜欢它。

The actual code I was doing this for is: 我这样做的实际代码是:

ftp.ConnectMode = job.FTPUsePassiveMode ? FTPConnectMode.PASV : FTPConnectMode.ACTIVE;

Your code should read: 您的代码应为:

str = b ? "true" : "false";

However, this is akin to just calling b.ToString().ToLower() . 但是,这类似于只调用b.ToString().ToLower() That said, I suspect your actual use-case is a little more complex than just converting the Boolean value to a string. 就是说,我怀疑您的实际用例比将布尔值转换为字符串还要复杂。

Update 更新资料
As indicated in the comments, the conditional operator returns a value; 如注释中所示, 条件运算符返回一个值; it is not for control flow like if / else . 它不像if / else那样用于控制流。

str = b ? "true" : "false";

But you could just do this: 但是您可以这样做:

str = b.ToString();

Or even cut out the middleman altogether: 甚至完全切掉中间人:

Console.WriteLine(b);

The ternary operator doesn't allow for statement switching, only value switching. 三元运算符不允许语句切换,仅允许值切换。 You want to do this: 您想这样做:

str= b ? "true" : "false"

(obviously b.ToString() ) is a better solution for this particular problem, but I'm assuming this is just an example). (显然b.ToString() )是解决此特定问题的更好解决方案,但我假设这只是一个示例)。

其他人说的话,以及: http//msdn.microsoft.com/en-us/library/ty67wk28.aspx

str = (b) ? "true" : "false";

三元运算符不能是C#中语句的顶层,因为C#要求顶层表达式具有副作用。

Just out of curiosity, why not just do this: 出于好奇,为什么不这样做:

bool b = true;
string str = b.ToString();

In .NET, value types automatically convert their value to a string when .ToString() is called...including booleans. 在.NET中,值类型在调用.ToString()时会自动将其值转换为字符串,包括布尔值。

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

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