- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - phát hiện rò rỉ bộ nhớ Ruby/Ruby on Rails
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
演示示例代码:
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?
我的问题是它们有什么区别以及为什么。提前致谢。
câu trả lời hay nhất
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 writtenx 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 thatx
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 ifVà
is implicitly convertible to the type ofx
or the operator is a shift operator, then the operation is evaluated asx = (T)(x op y)
, Ở đâuT
is the type ofx
, except thatx
is evaluated only once.
第二个项目符号就是这里发生的事情。没有将 char
值相加的运算符 - Đúng 是一个 int +(int, int)
运算符,这是被选中的 - 并且存在从 số nguyên
đến char
的显式转换。
所以这样:
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/
Tôi là một lập trình viên xuất sắc, rất giỏi!