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

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社区。

其他回答

string 是.NET 框架中的 String 的标志。

在哪里“String”实际上是 System.String。

我会说它们是可交换的,没有区别什么时候和在哪里你应该使用一个或另一个。

最好是和你所使用的相一致。

对于什么是值得的,我使用链来宣布类型 - 变量,属性,回报值和参数. 这与其他系统类型的使用一致 - int, bool, var 等(尽管 Int32 和 Boolean 也是正确的)。

我使用 String 在 String 类上使用静态方法,如 String.Split() 或 String.IsNullOrEmpty()。我觉得这更有意义,因为方法属于一个类,并且与我使用其他静态方法一致。

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

字符串为变量

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

如:

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

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

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

上述的一切基本上是正确的,一个人可以检查它。

public static void Main()
{
    var s = "a string";
}

编辑并打开.exe 与 ildasm 查看

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       8 (0x8)
  .maxstack  1
  .locals init ([0] string s)
  IL_0000:  nop
  IL_0001:  ldstr      "a string"
  IL_0006:  stloc.0
  IL_0007:  ret
} // end of method Program::Main

然后变成线条和线条,编译,打开与 ildasm 并看到 IL 不会改变. 它也显示语言的创作者在定义变量时更喜欢线条(spoiler:当呼叫会员时,他们更喜欢线条)。

字符串和字符串之间的微小差异在C#. 字符串只是系统的标志. 字符串. 两个字符串和字符串都是以相同的方式编写的. 答案是非常简单的. 字符串是关键词提供有限的功能,主要使用字符串创建变量如(字符串名称 = “Abrar”). 或者我们可以说这是一个数据类型我们使用特殊的字符串。

正如你所知道的,字符串只是 System.String 的名称,但我应该使用什么?它只是个人偏好。

在我的情况下,我喜欢使用字符串而不是使用 System.String 因为 String 需要使用 System 的名称空间;或者使用 System.String 的全名。

所以我相信 alias string 是为了简单而创建的,我喜欢它!