这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
当前回答
坦率地说,在实践中通常没有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 是 CTS(通用类型系统)中的字符串的名称。
您不需要进口名称空间(使用系统;)来使用字符串,因为它是一个全球的名称 System.String。
要了解更多关于 Alias 的信息,您可以查看此链接。
至少有四种差异:
字符串是保留的单词,但字符串只是一个类名称,这意味着字符串本身不能作为变量名称使用。
2、你不能使用 String 而不“使用系统”。所以你用“string”写得更少。
3、“String”比“string”更好地命名公约,因为它是一种不变的类型。
“String”是大多数编辑器中突出的C#关键字和合成,但不是“String”。
String(System.String)是基类图书馆的一个类。 string(下一个案例)是C#的备份工作,这是System.String的标志。 Int32 vs int是一种类似的情况,如Boolean vs. bool. 这些C#语言特定的关键词允许您以类似于C的风格宣布原始性。
.NET 类型与其他对象类型相同的颜色(值类型是合适的对象,毕竟)。
条件和控制的关键词(如如果,交换和返回)是下层和彩色黑蓝色(默认情况下)。
考虑一下:
String someString;
string anotherString;