这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
当前回答
有一个区别 - 您不能使用 String 没有使用系统; 提前。
其他回答
标签: 代表一类
字符串: 代表一个 alias
这只是微软的编码协议。
坦率地说,在实践中通常没有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社区。
string 是 System.String 的 C# 中的一个 alias. 所以技术上,没有区别. 它就像 int vs. System.Int32.
至于指导方针,一般建议在您提到对象时使用字符串。
吉。
string place = "world";
同样,我认为一般建议使用 String 如果你需要具体提到课堂。
吉。
string greet = String.Format("Hello {0}!", place);
这是微软在其例子中使用的风格。
似乎该领域的指导方针可能已经改变了,因为StyleCop现在强制使用C#特定的联盟。
只是为了完整性,这里是一个与相关信息的脑跳动......
正如其他人指出的那样, 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......相反的类型的生产,用于变量声明,例如,它不表明任何其他差异。
一个很好的方式来谈论它是线条是一个数据类型,在那里线条是一个类型,每一个都有不同的方法,使用哪一个取决于你的需要。