ch == 0); 我没有收到任何错误。C# 是强类型的,在这种情况下-6ren">
gpt4 book ai didi

C# 转换问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:22:36 25 4
gpt4 key购买 nike

为什么要写

char ch = 0;

如我所料,我得到了编译器错误

bool allZero = "000".All(ch => ch == 0);

我没有收到任何错误。C# 是强类型的,在这种情况下我更愿意发出警告。

那是我的软件中的错误。

最佳答案

这在 C# 语言规范中有解释。

6.1.2 隐式数字转换指出:

The implicit numeric conversions are:

(... some text omitted)

• From char to ushort, int, uint, long, ulong, float, double, or decimal.

并继续明确声明:

There are no implicit conversions to the char type, so values of the other integral types do not automatically convert to the char type

7.3.6.2 二进制数字提升指出:

Binary numeric promotion occurs for the operands of the predefined +, –, *, /, %, &, |, ^, ==, !=, >, <, >=, and <= binary operators. Binary numeric promotion implicitly converts both operands to a common type which, in case of the non-relational operators, also becomes the result type of the operation. Binary numeric promotion consists of applying the following rules, in the order they appear here:

• If either operand is of type decimal, the other operand is converted to type decimal, or a binding-time error occurs if the other operand is of type float or double.

(... some text omitted)

• Otherwise, both operands are converted to type int.

所以当 char == 0 被编译时,编译器会在生成比较代码之前将 char 提升为 int。

标准中没有任何内容允许将 int 隐式转换为 char(即使它是 有效范围内的常量值code>char),事实上它被明确禁止 - 这就是为什么 char ch = 0; 被允许的原因。

关于C# 转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47071897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com