代码之家  ›  专栏  ›  技术社区  ›  Matthew Scharley

为什么C#不为char定义加法操作?

c#
  •  8
  • Matthew Scharley  · 技术社区  · 16 年前

    Related to this question.

    string foo = 'a' + 'b'; // Fails with an invalid int -> string conversion
    

    char

    编辑: 普遍的共识是,与其说没有一个定义,不如说我期望被定义的那个没有定义。

    6 回复  |  直到 9 年前
        1
  •  15
  •   Eric Lippert    16 年前

    其次,回答你的“为什么不呢?”——字符有点奇怪。它们的存储是短整数,但它们的语义是字符串中字符的语义。那么,char应该被视为整数形式,还是短字符串?在这种情况下,语言设计者决定效仿C等早期语言,在对字符进行不涉及字符串的数学运算时,将字符视为整数。如果你想把它们当作短字符串来处理,有很多方法可以将字符转换为字符串。正如另一个答案所暗示的那样,追加空字符串明确地“告诉”编译器“这个操作是针对字符串的,而不是针对字符的整数值”。

        2
  •  7
  •   John Gietzen    16 年前

    string foo = String.Concat('a', 'b');
    

    String.Format

        3
  •  3
  •   Bob Kaufman    16 年前

    要实现您的期望,请执行以下操作

    String foo = "a" + "b";  // double quotes = single-character strings to concatenate
    
        4
  •  3
  •   Jez    16 年前

    string str = String.Format("{0}{1}", 'a', 'b');
    
        5
  •  1
  •   Paul Sasik    11 年前

    string foo2 = 'a' + "" + 'b'; //  Succeeds
    string foo3 = 'a'.ToString() + 'b'.ToString(); // Succeeds
    string foo4 = string.Concat('a', 'b'); // Succeeds
    

        6
  •  0
  •   Konstantin Spirin    16 年前

    您可以对字符串使用重载加法运算符,并尝试以下操作:

    var result = "" + 'a' + 'b';
    

    var result = 'a' + 'b' + "";  // BAD !!!!!
    

    因为它会给你