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

标签 c#

演示示例代码:

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/

相关文章:

c# - 存在差异时如何让 NUnit 集合比较调用 ToString

javascript - 使用 WebDriver 扩展 JavaScript 菜单

C# 3.0 从字符串中删除字符

c# - 如何使用谓词实现匹配算法?

c# - 使用 C# 的简单正则表达式帮助(包括正则表达式模式)

c# - 如何将 List<T> 传递给 T 实现的另一个类型列表

c# - 将输出文件保存到用户文件夹

c# - 使用 Entity Framework 更改跟踪器跟踪集合的更改

c# - 我如何重构这两个 C# 函数以从它们所作用的特定类属性中抽象出它们的逻辑?

c# - 当前类型 IUserStore<ApplicationUser> 和 DbConnection 分别是接口(interface)和抽象类,无法构造