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

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

当前回答

在我所知道的范围内,字符串只是 System.String 的名称,类似的字符串存在于 Bool, Object, Int... 唯一微妙的区别是,你可以使用字符串,而没有“使用系统;” 指令,而 String 需要它(否则,你应该指定 System.String 完整)。

关于什么是最好的使用,我猜这是一个口味问题,我个人更喜欢链条,但我不是一个宗教问题。

其他回答

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

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   |

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

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

首先,两个字符串和字符串都不是相同的,有一个区别:字符串不是一个关键字,它可以用作识别器,而字符串是关键字,不能用作识别器。

我试图用不同的例子来解释: 首先,当我把字符串 s 放进 Visual Studio 并将它转移到我获得(没有颜色):

文档位于 https://msdn.microsoft.com/en-us/library/362314fe.aspx. 第二个句子说“string 是.NET 框架中的 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 ]