Fork me on GitHub

在C#中大String 和string之间有什么区别?

问:string 和 String 的区别是什么?

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

 答1:

string是C#中System.String的别名。所以从技术上讲,没有什么区别。就像int 和 System.Int32一般情况下,我建议在使用string来引用对象。

例如:

string place = "world";

如果你需要特指这个类的话,我建议使用String

例如:

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

答2:

System.String是.net字符串类 - 在C#中stringSystem.String的别名 - 所以在使用中它们是相同的

如果你发现自己构建的系统需要指定你使用的整数的大小,所以倾向于使用Int16Int32UInt16UInt32等,那么使用String可能看起来更自然 - 而当在不同的 .net语言要使其变得更容易理解的话,我会使用string和int。

答3:

在反射机制中不能使用string,并且你必须使用String

答4:

在没有using System的情况下,你不能使用String。

答5:

string是个保留词,但是String只是一个类名。这意味着string本身不能用作变量名。

如果出于某种原因,你需要一个名为string的变量,那么你只会看到其中的第一个编译器:

StringBuilder String = new StringBuilder();  // compiles
StringBuilder string = new StringBuilder();  // doesn't compile 

如果你真的想要一个名为string的变量名,你可以用@作为前缀:

StringBuilder @string = new StringBuilder();

另一个关键区别是:Stack Overflow会以不同的方式突出显示它们。

答6:

String代表System.String并且这是一个.NET框架类型。string在C#语言中化名System.String.在IL中(中间语言),这两种方法都被汇编成System.String,所以没有区别。如果你用C#编写代码,我更希望是string,因为它是一个C#类型别名,并且被C#程序员所熟知。

或者说是(intSystem.Int32)。

答7:

string的别名System.String,它们编译成相同的代码,因此在执行时没有任何区别。以下为C#中完整的清单别名:

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

 

posted @ 2020-09-13 12:09  gentleKay  阅读(271)  评论(0编辑  收藏  举报