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

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

当前回答

基本上,在 C# 中,线和线之间没有区别。

String 是 System.String 中的.NET 框架中的一个类,而较低的案例字符串则是 System.String 的标志。

登录两个类型的完整名称可以证明这一点

string s1= "hello there 1";
String s2 = "hello there 2";
        
Console.WriteLine(s1.GetType().FullName); // System.String
Console.WriteLine(s2.GetType().FullName); // System.String

大多数开发人员使用字符串在C#中声明变量,并使用System.String类使用任何内置的字符串方法,例如,String.IsNullOrEmpty()方法。

其他回答

标签: 代表一类

字符串: 代表一个 alias

这只是微软的编码协议。

实际上没有区别

关键字 C# 连接地图到.NET 类型的 System.String - 这是一个标签,保持到语言的名称公约。

虽然 String 是一个保留的 C# 关键词,总是有一个固定的含义, String 只是一个常见的识别器,可以提到任何东西. 根据当前类型的成员,当前的名称空间和应用的使用指令和他们的位置, String 可能是一个值或类型与全球::System.String 不同。

我将提供两个例子,其中使用指令不会有助于。


class MySequence<TElement>
{
  public IEnumerable<TElement> String { get; set; }

  void Example()
  {
    var test = String.Format("Hello {0}.", DateTime.Today.DayOfWeek);
  }
}

更糟糕的是: 說 String.Concat(someSequence) 將很可能(取決於使用) 去 Linq 擴展方法 Enumerable.Concat. 它不會去到静态方法 string.Concat。


其次,当 String 是另一种类型时,它在当前类型内定位:

class MyPiano
{
  protected class String
  {
  }

  void Example()
  {
    var test1 = String.Format("Hello {0}.", DateTime.Today.DayOfWeek);
    String test2 = "Goodbye";
  }
}

然而,两者之间没有区别 - 行似乎是考虑到其他开发者的源代码时最受欢迎的选项。

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

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

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

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

StringBuilder @string = new StringBuilder();

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