这两者之间有什么区别,我应该使用哪一个?
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 |
其他回答
坦率地说,在实践中通常没有System.String和 string之间的区别。
所有类型在 C# 是对象,所有衍生于 System.Object 类. 一个区别是,字符串是一个 C# 关键字,字符串可以用作变量名称. System.String 是这个类型的常规.NET 名称,字符串是方便的 C# 名称. 这里是一个简单的程序,显示 System.String 和字符串之间的区别。
string a = new string(new char[] { 'x', 'y', 'z' });
string b = new String(new char[] { 'x', 'y', 'z' });
String c = new string(new char[] { 'x', 'y', 'z' });
String d = new String(new char[] { 'x', 'y', 'z' });
MessageBox.Show((a.GetType() == typeof(String) && a.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((b.GetType() == typeof(String) && b.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((c.GetType() == typeof(String) && c.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((d.GetType() == typeof(String) && d.GetType() == typeof(string)).ToString()); // shows true
@JonSkeet 在我的编辑器中
public enum Foo : UInt32 { }
我是Visual Studio 2015社区。
正如你所知道的,字符串只是 System.String 的名称,但我应该使用什么?它只是个人偏好。
在我的情况下,我喜欢使用字符串而不是使用 System.String 因为 String 需要使用 System 的名称空间;或者使用 System.String 的全名。
所以我相信 alias string 是为了简单而创建的,我喜欢它!
首先,两个字符串和字符串都不是相同的,有一个区别:字符串不是一个关键字,它可以用作识别器,而字符串是关键字,不能用作识别器。
我试图用不同的例子来解释: 首先,当我把字符串 s 放进 Visual Studio 并将它转移到我获得(没有颜色):
文档位于 https://msdn.microsoft.com/en-us/library/362314fe.aspx. 第二个句子说“string 是.NET 框架中的 String 的标志。
string 是.NET 框架中的 String 的标志。
在哪里“String”实际上是 System.String。
我会说它们是可交换的,没有区别什么时候和在哪里你应该使用一个或另一个。
最好是和你所使用的相一致。
对于什么是值得的,我使用链来宣布类型 - 变量,属性,回报值和参数. 这与其他系统类型的使用一致 - int, bool, var 等(尽管 Int32 和 Boolean 也是正确的)。
我使用 String 在 String 类上使用静态方法,如 String.Split() 或 String.IsNullOrEmpty()。我觉得这更有意义,因为方法属于一个类,并且与我使用其他静态方法一致。
字符串是 System.String 的简称,字符串或 System.String 是 CTS(通用类型系统)中的字符串的名称。