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

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

当前回答

如果有用的是真正看到没有线和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 是为了召唤其他 String 类方法

如:

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

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

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

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

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

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

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

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

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

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

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

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:当呼叫会员时,他们更喜欢线条)。

string 是 System.String 的 C# 中的一个 alias. 所以技术上,没有区别. 它就像 int vs. System.Int32.

至于指导方针,一般建议在您提到对象时使用字符串。

吉。

string place = "world";

同样,我认为一般建议使用 String 如果你需要具体提到课堂。

吉。

string greet = String.Format("Hello {0}!", place);

这是微软在其例子中使用的风格。

似乎该领域的指导方针可能已经改变了,因为StyleCop现在强制使用C#特定的联盟。