这两者之间有什么区别,我应该使用哪一个?
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社区。
其他回答
我更喜欢使用线条,因为这种类型是如此使用,我不希望合成亮度将其与所有其他类混合。虽然它是一个类,它被使用更像原始,所以我认为不同的亮度颜色是合适的。
如果你正确点击字符串的关键字,然后从背景菜单中选择去定义,它会带你到字符串类 - 它只是合成糖,但它提高了可读性 imo。
在 C# 中,线和线之间没有重大区别。
String 是系统名称空间中的.NET 框架中的一个类,完全合格的名称是 System.String。
但是,它建议使用字符串,同时声明变量如:
string str = "Hello";
我们可以使用 String 同时使用任何内置方法为 String.IsNullOrEmpty(等线条。
此外,这两者之间的区别就像在使用 String 之前,我们必须在 CS 文件中输入系统名称空间,并且可以直接使用 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 ]
string 是 System.String 的 C# 中的一个 alias. 所以技术上,没有区别. 它就像 int vs. System.Int32.
至于指导方针,一般建议在您提到对象时使用字符串。
吉。
string place = "world";
同样,我认为一般建议使用 String 如果你需要具体提到课堂。
吉。
string greet = String.Format("Hello {0}!", place);
这是微软在其例子中使用的风格。
似乎该领域的指导方针可能已经改变了,因为StyleCop现在强制使用C#特定的联盟。
图像结果为 string vs String www.javatpoint.com 在 C# 中, string 是.NET 框架中的 string 类的 alias. 事实上,每个 C# 类型都有.NET 的同等值. 另一个小差异是,如果你使用 string 类,你需要进口系统名称空间,而你不需要在使用 string 关键词时进口名称空间。