这两者之间有什么区别,我应该使用哪一个?

string s = "Hello world!";
String s = "Hello world!";

当前回答

坦率地说,在实践中通常没有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社区。

其他回答

这是一个协议问题,真的. 字符串只是看起来更像C/C++风格. 通用协议是使用你所选择的语言提供的任何缩写(int/Int为Int32)。 这也适用于“对象”和十数。

理论上,这可能有助于将代码转移到某些未来的64位标准,其中“int”可能意味着Int64,但这不是问题,我会期望任何升级巫师将改变任何int引用到Int32无论如何只是安全。

StyleCop 规则,默认情况下,将允许您使用字符串作为一个 C# 代码风格的最佳实践,除非提到 System.String 静态功能,如 String.Format, String.Join, String.Concat 等。

下面的案例字符串是 System.String 的标志,它们在 C# 中是相同的。

有一个讨论是否应该使用系统类型(System.Int32,System.String等)类型或C#联盟(int, string等)。我个人认为你应该使用C#联盟,但这只是我的个人偏好。

有一个区别 - 您不能使用 String 没有使用系统; 提前。

字符串是保留的单词,但字符串只是一个类名称,这意味着字符串本身不能作为变量名称使用。

如果出于某种原因,你想要一个变量称为字符串,你只会看到这些编辑中的第一个:

StringBuilder String = new StringBuilder();  // compiles
StringBuilder string = new StringBuilder();  // doesn't compile 

如果你真的想要一个变量名称,称为字符串,你可以使用 @ 作为预定:

StringBuilder @string = new StringBuilder();

另一个关键差异:Stack Overflow以不同的方式突出它们。