这两者之间有什么不同,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
说实话,在实践中,System.String
和string
通常没有区别。
C#中的所有类型都是对象,都派生自System.Object
类。一个不同之处在于,string是C#的关键字,而String
可以用作变量名。System.String
是这种类型的传统.NET名称,而string是方便的C#名称。下面是一个简单的程序,演示了System.String
和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
is equal to System.String
string
"就等同于"System.String
"。System.String str;
编译器会显示可能的修复方法以进行优化,应用该修复方法后,它将如下所示
string str;
Jeffrey Richter写道:
另一种思考方式是,C#编译器会自动假定在您所有的源代码文件中都有以下
using
指令:
using int = System.Int32;
using uint = System.UInt32;
using string = System.String;
...
我见过许多开发人员感到困惑,不知道在他们的代码中使用string还是String。因为在C#中,string(一个关键字)与System.String(一个FCL类型)完全对应,没有区别,所以两者都可以使用。
string
进行声明,而使用String
访问静态字符串方法。'string'
声明使用预定义类型'string'
的字段���属性等,因为C#规范告诉我这是很好的风格。'String'
来使用系统定义的方法,如String.Compare等。它们最初是在'System.String'上定义的,而不是在'string'上定义的。在这种情况下,'string'
只是一个别名。'String'
或'System.Int32'。也就是说,如果我从其他地方获取数据,则会将其反序列化为System.Int32而不是'int',如果原始定义是C#系统之外的其他内容。这两者没有区别,您可以在代码中使用任何一个。
System.String
是一个类(引用类型),定义在命名空间 System
中的 mscorlib
中。换句话说,System.String
是 CLR
中的一种类型。
string
是 C#
中的关键字。
string
,因为这种类型经常使用,我不想让语法高亮混在所有其他类中。虽然它是一个类,但它更像一个原始的类型,因此我认为不同的高亮颜色是合适的。string
关键字,并从上下文菜单中选择转到定义
,它会带你到String
类——这只是一种语法糖,但它提高了可读性。
string
是 C# 语法的一个 词法 构造,而System.String
只是一种类型。无论任何规范中提到的 显式 差异如何,仍然存在这种隐含的差异,可能会带来一些歧义。语言本身必须以一种不需要考虑 BCL 中的特定类的方式支持string
。 - Kirk Wollstring
存在问题。需要缩写System.String
,但作为别名,它看起来非常相似,但不完全相同。然而,经过几年的C#编程,我认为,安全起见,可以直接使用string
和string.Format()
,不用担心System.String
。 - RolandSystem.String
类还在,而string
关键字仍然是它的别名,就像System.Int32
和int
一样。它们实际上是同一个东西。 - Craig Tullis