代码之家  ›  专栏  ›  技术社区  ›  John M Gant aman_novice

对于单字符值使用char而不是string有什么好处吗?

  •  5
  • John M Gant aman_novice  · 技术社区  · 17 年前

    为了。NET字段和属性根据定义只包含一个字符,将它们定义为char而不是string有什么好处吗?或者这是char数据类型的错误使用吗?

    4 回复  |  直到 17 年前
        1
  •  12
  •   Noldorin    17 年前

    对, char

    从另一个角度考虑:当想在代码中使用整数值时,你会创建一个大小为1的整数数组吗?当然不会,因为虽然它能完成工作,但它相当

    int[] value = new int[1] { 123 };
    value[0] = 456;
    

    致:

    int value = 123;
    value = 456;
    

    string

    此外,当涉及到操纵代码中的值时,您应该发现将字段设置为更合适的数据类型(即。

    就性能而言,我不会想象使用 会给你带来任何重大的开销。好吧,所以它占用了 略微 应该 选择 .

        2
  •  4
  •   Andrew Hare    17 年前

    A. Char 1个字符 String

    。始终创建有用的抽象概念。换句话说,我会这样定义你的字段:

    enum Gender { Male, Female }
    
    class Foo
    {
        Gender gender;
        Char middleInitial;
        Boolean indicator;
    }
    

        3
  •  2
  •   TheTXI    17 年前

        4
  •  1
  •   Cade Roux    17 年前

    字符串类将有一些开销。如果你有char,你需要用0x00表示空吗 <space>

    Person.Gender == Female 和 if (!Person.IsDeceased) {}