这两者之间有什么区别,我应该使用哪一个?

string s = "Hello world!";
String s = "Hello world!";

当前回答

字符串是字符串的类别. 如果您从使用声明中删除系统名称空间,您可以看到字符串已经消失,但字符串仍然在这里. 字符串是字符串的关键词. 如 int 和 Int32 短语和 Int16 长语和 Int64 因此,关键词只是使用一个类别的一些词。

其他回答

String(System.String)是基类图书馆的一个类。 string(下一个案例)是C#的备份工作,这是System.String的标志。 Int32 vs int是一种类似的情况,如Boolean vs. bool. 这些C#语言特定的关键词允许您以类似于C的风格宣布原始性。

坦率地说,在实践中通常没有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社区。

StyleCop 规则,默认情况下,将允许您使用字符串作为一个 C# 代码风格的最佳实践,除非提到 System.String 静态功能,如 String.Format, String.Join, String.Concat 等。

与其他程序员中似乎是常见的做法相反,我更喜欢线条超越线条,只是为了强调线条是一种参考类型,正如Jon Skeet提到的那样。

两者都是相同的,区别在于你如何使用它。

字符串为变量

String 是为了召唤其他 String 类方法

如:

string fName = "John";
string lName = "Smith";

string fullName = String.Concat(fName,lName);

if (String.IsNullOrEmpty(fName))
{
  Console.WriteLine("Enter first name");
}