这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
当前回答
字符串等于 System.String 在 VS2015 如果您写下此:
System.String str;
如何编辑器将显示潜在的修复,以优化它,并在应用该修复后,它将看起来像这个
string str;
其他回答
在 C# 中, string 是 System.String (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 |
上述的一切基本上是正确的,一个人可以检查它。
public static void Main()
{
var s = "a string";
}
编辑并打开.exe 与 ildasm 查看
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 8 (0x8)
.maxstack 1
.locals init ([0] string s)
IL_0000: nop
IL_0001: ldstr "a string"
IL_0006: stloc.0
IL_0007: ret
} // end of method Program::Main
然后变成线条和线条,编译,打开与 ildasm 并看到 IL 不会改变. 它也显示语言的创作者在定义变量时更喜欢线条(spoiler:当呼叫会员时,他们更喜欢线条)。
下面的案例字符串是 System.String 的标志,它们在 C# 中是相同的。
有一个讨论是否应该使用系统类型(System.Int32,System.String等)类型或C#联盟(int, string等)。我个人认为你应该使用C#联盟,但这只是我的个人偏好。
基本上,在 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()方法。