[英]Difference between char in Java and C# (particular problem with (char)-1)
char x = (char)-1;
is valid in Java, but shows me the error ( Overflow in constant value computation ) 在Java中有效,但显示错误( 常量值计算中的溢出 )
Should I use a different datatype in C#? 我应该在C#中使用其他数据类型吗?
The error occurs because C# is smarter about literals ("constant computation"). 发生该错误是因为C#对文字(“常量计算”)更为精明。 In C# one could do...
在C#中可以做到...
int x = -1;
char c = (char)x;
int y = c;
// y is 0xffff, as per Java
However, do note that 0xFFFF is an invalid Unicode character :) 但是,请注意0xFFFF是无效的Unicode字符 :)
Happy coding. 快乐的编码。
Using unchecked
will also "work": 使用
unchecked
也会“起作用”:
unchecked {
char x = (char)-1;
}
Here's the definition of the C# char
type ; 这是C#
char
类型的定义 ; it's a 16-bit Unicode character, same as in Java . 与Java中一样,它是16位Unicode字符。 If you are just looking for a 16-byte signed value, then you might want a
short
. 如果您只是在寻找一个16字节的带符号值, 则可能需要
short
。
For your reference, here is a list of the integral types available to you in C#. 供您参考, 这是 C#中可用的整数类型的列表 。
You can also use an unchecked
statement such as unchecked { char x = (char)-1; }
您还可以使用
unchecked
语句,例如unchecked { char x = (char)-1; }
unchecked { char x = (char)-1; }
; unchecked { char x = (char)-1; }
; however, if it were me and I was, for instance, using -1
to represent an error value or some other marker, I would probably just use: char x = (char)0xFFFF;
但是,如果是我,例如使用
-1
表示错误值或其他标记,我可能只使用: char x = (char)0xFFFF;
which gives you the same result, and a way of checking for an invalid value, without needing to circumvent the type check. 这将为您提供相同的结果,并提供一种检查无效值的方式,而无需绕过类型检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.