seed + =(char)1之间有什么区别;和种子=种子+(char)1;

时间:2018-02-14 10:08:23

标签: c#

我在C#中运行以下程序:

using System;

class MainClass {
    public static void Main (string[] args) {
        char seed = 'a';
        char EndValue='z';
        while ( seed <= EndValue){
            Console.WriteLine(seed);
            seed+=(char)1;   
        }
    }
}

此工作正常,但将seed+=(char)1;更改为seed = seed + (char)1;

抛出错误

  

退出状态1

     

main.cs(9,8):错误CS0266:无法隐式转换类型int' to char&#39;。存在显式转换(您是否错过了演员?)   编译失败:1个错误,0个警告&#34;在repl.it

https://repl.it/@nkshschdv/iteration-over-char-variable

1 个答案:

答案 0 :(得分:1)

让我们看看你的代码实际上在做什么。 如果i是int

i += 1i = i + 1

相同

所以在你的情况下 seed+=(char)1;seed = (char)(seed + 1);

相同

所以seed = seed + (char)1;只是缺少char转换,这在你的方式中是隐含的。

您也可以将其写为seed = (char)((int)seed + 1);,但C#会自动处理+运算符的char到int转换。正如Dennis_E指出的那样,由于这种隐式的int转换,你可以调用seed++;