这两者之间有什么区别,我应该使用哪一个?
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。
要了解更多关于 Alias 的信息,您可以查看此链接。
C# 是与 CLR 一起使用的语言。
字符串是 C# 的类型。
System.String 是 CLR 中的一种类型。
当您使用 C# 与 CLR 行一起时,将被地图到 System.String。
理论上,你可以实施一个C#编译器,产生Java bytecode. 这个编译器的敏感实施可能将地图链到java.lang.String,以便与Java运行时间图书馆互动。
然而,两者之间没有区别 - 行似乎是考虑到其他开发者的源代码时最受欢迎的选项。
只是为了完整性,这里是一个与相关信息的脑跳动......
正如其他人指出的那样, string 是 System.String 的 alias. 假设使用 String 编译到 System.String 的代码(即您没有使用某些不同的 String 类型的其他名称空间的指令),它们编译到相同的代码,所以在执行时间没有任何差异。
object: System.Object
string: System.String
bool: System.Boolean
byte: System.Byte
sbyte: System.SByte
short: System.Int16
ushort: System.UInt16
int: System.Int32
uint: System.UInt32
long: System.Int64
ulong: System.UInt64
float: System.Single
double: System.Double
decimal: System.Decimal
char: System.Char
在特征中,值类型联盟被称为“简单类型”。字母可以用于每个简单类型的恒定的值;没有其他值类型有字母形式可用。
有一個情況,你必須使用連結:當明確指定一個 enum 的基礎類型。
public enum Foo : UInt32 {} // Invalid
public enum Bar : uint {} // Valid
这只是一个问题,规格如何定义enum声明 - 结尾后的一部分必须是整体类型的生产,这是一个标志的sbyte, byte, short, ushort, int, uint, long, ulong, char......相反的类型的生产,用于变量声明,例如,它不表明任何其他差异。
字符串和字符串在所有方面都是相同的(除上面的“S”外)。
在大多数项目中,由于合成突出性而偏好下滑线。