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

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

当前回答

有一个实用的区别在线和线之间。

nameof(String); // compiles
nameof(string); // doesn't compile

這是因為字符串是一個關鍵字(在這種情況下,一個名稱),而字符串是一個類型。

同样的情况也适用于其他联盟。

| Alias     | Type             |
|-----------|------------------|
|  bool     |  System.Boolean  |
|  byte     |  System.Byte     |
|  sbyte    |  System.SByte    |
|  char     |  System.Char     |
|  decimal  |  System.Decimal  |
|  double   |  System.Double   |
|  float    |  System.Single   |
|  int      |  System.Int32    |
|  uint     |  System.UInt32   |
|  long     |  System.Int64    |
|  ulong    |  System.UInt64   |
|  object   |  System.Object   |
|  short    |  System.Int16    |
|  ushort   |  System.UInt16   |
|  string   |  System.String   |

其他回答

如果有用的是真正看到没有线和System.String之间的区别:

var method1 = typeof(MyClass).GetMethod("TestString1").GetMethodBody().GetILAsByteArray();
var method2 = typeof(MyClass).GetMethod("TestString2").GetMethodBody().GetILAsByteArray();

//...

public string TestString1()
{
    string str = "Hello World!";
    return str;
}

public string TestString2()
{
    String str = "Hello World!";
    return str;
}

两者都产生相同的 IL 比特序列:

[ 0, 114, 107, 0, 0, 112, 10, 6, 11, 43, 0, 7, 42 ]

字符串和字符串在所有方面都是相同的(除上面的“S”外)。

在大多数项目中,由于合成突出性而偏好下滑线。

我只是想把这个添加到Lfousts的答案,从Ritchers的书:

C# 语言规格说:“在风格问题上,使用关键字优于使用完整的系统类型名称。我不同意语言规格;我更喜欢使用 FCL 类型名称,完全避免原始类型名称。

我没有得到他的意见,直到我阅读完整的段落。

String(System.String)是基类图书馆的一个类。 string(下一个案例)是C#的备份工作,这是System.String的标志。 Int32 vs int是一种类似的情况,如Boolean vs. bool. 这些C#语言特定的关键词允许您以类似于C的风格宣布原始性。

事实上,每个 C# 类型都有一个相当于.NET. 作为另一个例子,在 C# 地图中简短和 int 到 Int16 和 Int32 在.NET. 因此,技术上没有线和线之间的区别,但在 C# 中,线是.NET 框架中的线类的标志。