这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
当前回答
String(System.String)是基类图书馆的一个类。 string(下一个案例)是C#的备份工作,这是System.String的标志。 Int32 vs int是一种类似的情况,如Boolean vs. bool. 这些C#语言特定的关键词允许您以类似于C的风格宣布原始性。
其他回答
@JaredPar(C#编辑器的开发者和繁荣的SO用户!)写了一篇关于这个问题的博客文章,我认为值得分享。
string vs. string 不是风格辩论
[...]
识别器 String 虽然没有具体的含义在 C#. 它是一个识别器,通过所有的名称搜索规则,如 Widget, 学生, 等... 它可以连接到链条或它可以连接到一个类型在另一个组合,其目的可能完全不同于链条. 更糟糕的是,它可以定义的方式,这样的代码,如 String s = “你好”; 继续编译。
[...]
所以请记住,当你看到 String vs. String 讨论时,这就是关于语法,而不是风格。 选择 String 会给你的代码基础带来微妙的意义. 选择 String 不是错误的,但它会让未来惊喜的门开放。
字符串是 System.String 的缩短,唯一的区别是,你不需要提到 System.String 名称空间,所以比 String 更好地使用字符串。
在 C# 中, string 是 System.String (String) 的短手版本,它们基本上是相同的。
它就像博尔和布莱恩,没有太大的区别。
虽然 String 是一个保留的 C# 关键词,总是有一个固定的含义, String 只是一个常见的识别器,可以提到任何东西. 根据当前类型的成员,当前的名称空间和应用的使用指令和他们的位置, String 可能是一个值或类型与全球::System.String 不同。
我将提供两个例子,其中使用指令不会有助于。
class MySequence<TElement>
{
public IEnumerable<TElement> String { get; set; }
void Example()
{
var test = String.Format("Hello {0}.", DateTime.Today.DayOfWeek);
}
}
更糟糕的是: 說 String.Concat(someSequence) 將很可能(取決於使用) 去 Linq 擴展方法 Enumerable.Concat. 它不會去到静态方法 string.Concat。
其次,当 String 是另一种类型时,它在当前类型内定位:
class MyPiano
{
protected class String
{
}
void Example()
{
var test1 = String.Format("Hello {0}.", DateTime.Today.DayOfWeek);
String test2 = "Goodbye";
}
}
坦率地说,在实践中通常没有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社区。