这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
当前回答
字符串是一种序列的字符集,用于代表文本。
序列对象是代表序列的 System.Char 对象的序列集,而 System.Char 对象与 UTF-16 代码单位相匹配。
String 对象的值是 System.Char 对象的序列收藏的内容,这个值是不可改变的(即它仅是阅读的)。
有关线条不变性的更多信息,请参见MSDN中的不变性和StringBuilder类部分。
内存中的 String 对象的最大尺寸为 2GB 或大约 1 亿个字符。
注意 : 答案是从 msdn 帮助部分提取的. 在 msdn String Class 主题中,您可以在此处查看完整内容。
其他回答
两者之间没有区别,您可以在代码中使用其中一个。
System.String 是一个类(参考类型)定义的 mscorlib 在名空间系统. 换句话说, System.String 是 CLR 的类型。
string 是 C# 的关键词
@JaredPar(C#编辑器的开发者和繁荣的SO用户!)写了一篇关于这个问题的博客文章,我认为值得分享。
string vs. string 不是风格辩论
[...]
识别器 String 虽然没有具体的含义在 C#. 它是一个识别器,通过所有的名称搜索规则,如 Widget, 学生, 等... 它可以连接到链条或它可以连接到一个类型在另一个组合,其目的可能完全不同于链条. 更糟糕的是,它可以定义的方式,这样的代码,如 String s = “你好”; 继续编译。
[...]
所以请记住,当你看到 String vs. String 讨论时,这就是关于语法,而不是风格。 选择 String 会给你的代码基础带来微妙的意义. 选择 String 不是错误的,但它会让未来惊喜的门开放。
只是为了完整性,这里是一个与相关信息的脑跳动......
正如其他人指出的那样, string 是 System.String 的 alias. 假设使用 String 编译到 System.String 的代码(即您没有使用某些不同的 String 类型的其他名称空间的指令),它们编译到相同的代码,所以在执行时间没有任何差异。
object: System.Object
string: System.String
bool: System.Boolean
byte: System.Byte
sbyte: System.SByte
short: System.Int16
ushort: System.UInt16
int: System.Int32
uint: System.UInt32
long: System.Int64
ulong: System.UInt64
float: System.Single
double: System.Double
decimal: System.Decimal
char: System.Char
在特征中,值类型联盟被称为“简单类型”。字母可以用于每个简单类型的恒定的值;没有其他值类型有字母形式可用。
有一個情況,你必須使用連結:當明確指定一個 enum 的基礎類型。
public enum Foo : UInt32 {} // Invalid
public enum Bar : uint {} // Valid
这只是一个问题,规格如何定义enum声明 - 结尾后的一部分必须是整体类型的生产,这是一个标志的sbyte, byte, short, ushort, int, uint, long, ulong, char......相反的类型的生产,用于变量声明,例如,它不表明任何其他差异。
坦率地说,在实践中通常没有System.String和 string之间的区别。
所有类型在 C# 是对象,所有衍生于 System.Object 类. 一个区别是,字符串是一个 C# 关键字,字符串可以用作变量名称. System.String 是这个类型的常规.NET 名称,字符串是方便的 C# 名称. 这里是一个简单的程序,显示 System.String 和字符串之间的区别。
string a = new string(new char[] { 'x', 'y', 'z' });
string b = new String(new char[] { 'x', 'y', 'z' });
String c = new string(new char[] { 'x', 'y', 'z' });
String d = new String(new char[] { 'x', 'y', 'z' });
MessageBox.Show((a.GetType() == typeof(String) && a.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((b.GetType() == typeof(String) && b.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((c.GetType() == typeof(String) && c.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((d.GetType() == typeof(String) && d.GetType() == typeof(string)).ToString()); // shows true
@JonSkeet 在我的编辑器中
public enum Foo : UInt32 { }
我是Visual Studio 2015社区。
string 是 System.String 的 C# 中的一个 alias. 所以技术上,没有区别. 它就像 int vs. System.Int32.
至于指导方针,一般建议在您提到对象时使用字符串。
吉。
string place = "world";
同样,我认为一般建议使用 String 如果你需要具体提到课堂。
吉。
string greet = String.Format("Hello {0}!", place);
这是微软在其例子中使用的风格。
似乎该领域的指导方针可能已经改变了,因为StyleCop现在强制使用C#特定的联盟。