这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
这两者之间有什么区别,我应该使用哪一个?
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 |
其他回答
有一个实用的区别在线和线之间。
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 |
字符串不是一个关键词,它可以用作识别器,而字符串是一种关键词,不能用作识别器。
字符串是保留的单词,但字符串只是一个类名称,这意味着字符串本身不能作为变量名称使用。
如果出于某种原因,你想要一个变量称为字符串,你只会看到这些编辑中的第一个:
StringBuilder String = new StringBuilder(); // compiles
StringBuilder string = new StringBuilder(); // doesn't compile
如果你真的想要一个变量名称,称为字符串,你可以使用 @ 作为预定:
StringBuilder @string = new StringBuilder();
另一个关键差异:Stack Overflow以不同的方式突出它们。
.NET 类型与其他对象类型相同的颜色(值类型是合适的对象,毕竟)。
条件和控制的关键词(如如果,交换和返回)是下层和彩色黑蓝色(默认情况下)。
考虑一下:
String someString;
string anotherString;
string 只是 System.String 的标志,编辑器将以相同的方式处理它们。
唯一的实用差异是你提到的合成突出,如果你使用String,你必须使用系统写作。