这两者之间有什么区别,我应该使用哪一个?
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社区。
我更喜欢使用线条,因为这种类型是如此使用,我不希望合成亮度将其与所有其他类混合。虽然它是一个类,它被使用更像原始,所以我认为不同的亮度颜色是合适的。
如果你正确点击字符串的关键字,然后从背景菜单中选择去定义,它会带你到字符串类 - 它只是合成糖,但它提高了可读性 imo。
关于这个问题的引用来自丹尼尔·索里斯的书。
所有预先定义的类型都是直接地图到底部的.NET 类型. C# 类型名称(string)只是对.NET 类型(String 或 System.String)的联盟,所以使用.NET 名称工作顺利,尽管这不受鼓励。
另一个没有提到的论点,最好是复活节案例:
System.String 是参考类型,参考类型名称是经典案例。
.NET 类型与其他对象类型相同的颜色(值类型是合适的对象,毕竟)。
条件和控制的关键词(如如果,交换和返回)是下层和彩色黑蓝色(默认情况下)。
考虑一下:
String someString;
string anotherString;