简体   繁体   English

在C#中可以将一个Char转换为Int32产生负值吗?

[英]In C# can casting a Char to Int32 produce a negative value?

或者它是否始终保证对所有可能的Chars都是正面的?

It's guaranteed to be non-negative. 它保证是非负面的。

char is an unsigned 16-bit value. char无符号的 16位值。

From section 4.1.5 of the C# 4 spec: 从C#4规范的4.1.5节:

The char type represents unsigned 16-bit integers with values between 0 and 65535. The set of possible values for the char type corresponds to the Unicode character set. char类型表示无符号的16位整数,其值介于0和65535之间char类型的可能值集对应于Unicode字符集。 Although char has the same representation as ushort , not all operations permitted on one type are permitted on the other. 尽管charushort具有相同的表示,但并非所有允许在一种类型上允许的操作都在另一种类型上。

由于char的范围是U + 0000到U + ffff,因此对Int32将始终为正。

Each 16-bit value ranges from hexadecimal 0x0000 through 0xFFFF and is stored in a Char structure. 每个16位值的范围从十六进制0x0000到0xFFFF,并存储在Char结构中。

Char Structure - MSDN 字符结构 - MSDN

See Microsoft's documentation 请参阅Microsoft的文档

There you can see, that Char is a 16 bit value in the range of U+0000 to U+ffff. 在那里你可以看到,Char是U + 0000到U + ffff范围内的16位值。 If you cast it to a Int32, there should be no negative value. 如果将其强制转换为Int32,则应该没有负值。

char可以明确地转换为ushortushort范围是0 to 65,535所以它总是正面的

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

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