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

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

当前回答

string 只是 System.String 的标志,编辑器将以相同的方式处理它们。

唯一的实用差异是你提到的合成突出,如果你使用String,你必须使用系统写作。

其他回答

我更喜欢使用线条,因为这种类型是如此使用,我不希望合成亮度将其与所有其他类混合。虽然它是一个类,它被使用更像原始,所以我认为不同的亮度颜色是合适的。

如果你正确点击字符串的关键字,然后从背景菜单中选择去定义,它会带你到字符串类 - 它只是合成糖,但它提高了可读性 imo。

两者都是相同的,区别在于你如何使用它。

字符串为变量

String 是为了召唤其他 String 类方法

如:

string fName = "John";
string lName = "Smith";

string fullName = String.Concat(fName,lName);

if (String.IsNullOrEmpty(fName))
{
  Console.WriteLine("Enter first name");
}

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

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   |

Jeffrey Richter 写道:

另一种方法是C#编译器自动假设您在所有源代码文件中使用下列指南:

using int = System.Int32;
using uint = System.UInt32;
using string = System.String;
...

我已经看到一些开发人员混淆了,不知道是否在他们的代码中使用线条或线条. 因为在C#线条(一个关键词)地图准确到System.String(一个FCL类型),没有区别,也可以使用。

基本上,在 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()方法。