这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
当前回答
然而,两者之间没有区别 - 行似乎是考虑到其他开发者的源代码时最受欢迎的选项。
其他回答
在 C# 中, string 是 System.String (String) 的短手版本,它们基本上是相同的。
它就像博尔和布莱恩,没有太大的区别。
但从编码指南的观点,最好使用字符串而不是字符串,这就是开发人员通常使用的。 例如,而不是使用 Int32 我们使用 int 作为 int 是 alias 到 Int32
FYI “关键字行仅仅是预先定义的类 System.String 的名称” - C# 语言规格 4.2.3 http://msdn2.microsoft.com/En-US/library/aa691153.aspx
string 是 System.String 的 C# 中的一个 alias. 所以技术上,没有区别. 它就像 int vs. System.Int32.
至于指导方针,一般建议在您提到对象时使用字符串。
吉。
string place = "world";
同样,我认为一般建议使用 String 如果你需要具体提到课堂。
吉。
string greet = String.Format("Hello {0}!", place);
这是微软在其例子中使用的风格。
似乎该领域的指导方针可能已经改变了,因为StyleCop现在强制使用C#特定的联盟。
另一个没有提到的论点,最好是复活节案例:
System.String 是参考类型,参考类型名称是经典案例。
如果有用的是真正看到没有线和System.String之间的区别:
var method1 = typeof(MyClass).GetMethod("TestString1").GetMethodBody().GetILAsByteArray();
var method2 = typeof(MyClass).GetMethod("TestString2").GetMethodBody().GetILAsByteArray();
//...
public string TestString1()
{
string str = "Hello World!";
return str;
}
public string TestString2()
{
String str = "Hello World!";
return str;
}
两者都产生相同的 IL 比特序列:
[ 0, 114, 107, 0, 0, 112, 10, 6, 11, 43, 0, 7, 42 ]