gpt4 book ai didi

c# - 关于将类型 'int' 隐式转换为 'char' ,为什么 `s[i] += s[j]` 和 `s[i] = s[i]+s[j] ` 不同

转载 作者:IT王子 更新时间:2023-10-29 04:24:20 24 4
gpt4 key购买 nike

演示示例代码:

public void ReverseString(char[] s) {
for(int i = 0, j = s.Length-1; i < j; i++, j--){
//s[i] = s[i]+s[j]; //<-- error
s[i] += s[j]; //<-- ok

s[j] = (char)(s[i] - s[j]); //<-- cast
s[i] -= s[j];
}
}

如上代码片段,while s[i] += s[j] 没有任何错误。其等价语句s[i] = s[i]+s[j]会报错如下

error CS0266: Cannot implicitly convert type 'int' to 'char'. An explicit conversion exists (are you missing a cast?

我的问题是它们有什么区别以及为什么。提前致谢。

最佳答案

Its equivalent statement s[i] = s[i]+s[j] will cause error as follows

这不是一个等价的声明,尽管我能理解您为什么期望它是等价的。来自 section 12.18.3 C# 5 ECMA 标准,围绕复合赋值:

An operation of the form x op= y is processed by applying binary operator overload resolution (§12.4.5) as if the operation was written x op y. Then,

  • If the return type of the selected operator is implicitly convertible to the type of x, the operation is evaluated as x = x op y, except that x is evaluated only once.
  • Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once.

第二个项目符号就是这里发生的事情。没有将 char 值相加的运算符 - 是一个 int +(int, int) 运算符,这是被选中的 - 并且存在从 intchar 的显式转换。

所以这样:

s[i] += s[j];

更等同于

s[i] = (char) (s[i] + s[j]);

...编译正常。

关于c# - 关于将类型 'int' 隐式转换为 'char' ,为什么 `s[i] += s[j]` 和 `s[i] = s[i]+s[j] ` 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55452604/

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