在String.Equals中使用C#ternary

Vit*_*tas 31 .net c#

这有效:

short value;
value = 10 > 4 ? 5 : 10;
Run Code Online (Sandbox Code Playgroud)

这有效:

short value;
value = "test" == "test" ? 5 : 10;
Run Code Online (Sandbox Code Playgroud)

这不起作用:

short value;
string str = "test";
value = "test" == str ? 5 : 10;
Run Code Online (Sandbox Code Playgroud)

这也不是:

short value;
string str = "test";
value = "test".Equals(str) ? 5 : 10;
Run Code Online (Sandbox Code Playgroud)

最后两种情况我收到以下错误:

Cannot implicitly convert type 'int' to 'short'.
An explicit conversion exists (are you missing a cast?)
Run Code Online (Sandbox Code Playgroud)

为什么我必须对最后两个案例进行演绎而不是对前两个案例进行演绎?

Tim*_*lds 45

short value;
value = 10 > 4 ? 5 : 10;             //1
value = "test" == "test" ? 5 : 10;   //2
string str = "test";
value = "test" == str ? 5 : 10;      //3
value = "test".Equals(str) ? 5 : 10; //4
Run Code Online (Sandbox Code Playgroud)

最后两个三元表达式(3,4)在编译时无法解析为常量.因此,编译器将510作为int文字对待,并且整个三元表达式的类型是int.要从a转换int为a,short需要显式转换.

前两个三元表达式(1,2)可以在编译时解析为常量.常量值是a int,但编译器知道它适合a short,因此不需要任何转换.

为了好玩,试试这个:

value = "test" == "test" ? 5 : (int)short.MaxValue + 1;
Run Code Online (Sandbox Code Playgroud)

  • 供参考:编译器实现的这种行为称为[Constant Folding](http://en.wikipedia.org/wiki/Constant_folding) (5认同)