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

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

当前回答

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

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

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

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

StringBuilder @string = new StringBuilder();

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

其他回答

您不需要进口名称空间(使用系统;)来使用字符串,因为它是一个全球的名称 System.String。

要了解更多关于 Alias 的信息,您可以查看此链接。

在 MSDN 文档的背景下, String 类像任何其他数据类型(例如 XmlReader、StreamReader)一样在 BCL 中文档。

字符串被记录为一个关键字(C#参考)或任何基本的C#语言构造(例如,为,同时,默认)。

参考。

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

上述的一切基本上是正确的,一个人可以检查它。

public static void Main()
{
    var s = "a string";
}

编辑并打开.exe 与 ildasm 查看

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       8 (0x8)
  .maxstack  1
  .locals init ([0] string s)
  IL_0000:  nop
  IL_0001:  ldstr      "a string"
  IL_0006:  stloc.0
  IL_0007:  ret
} // end of method Program::Main

然后变成线条和线条,编译,打开与 ildasm 并看到 IL 不会改变. 它也显示语言的创作者在定义变量时更喜欢线条(spoiler:当呼叫会员时,他们更喜欢线条)。

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

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