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

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

当前回答

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

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

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

其他回答

如果有用的是真正看到没有线和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 是 System.String 的 C# 中的一个 alias. 所以技术上,没有区别. 它就像 int vs. System.Int32.

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

吉。

string place = "world";

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

吉。

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

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

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

只是为了完整性,这里是一个与相关信息的脑跳动......

正如其他人指出的那样, string 是 System.String 的 alias. 假设使用 String 编译到 System.String 的代码(即您没有使用某些不同的 String 类型的其他名称空间的指令),它们编译到相同的代码,所以在执行时间没有任何差异。

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

在特征中,值类型联盟被称为“简单类型”。字母可以用于每个简单类型的恒定的值;没有其他值类型有字母形式可用。

有一個情況,你必須使用連結:當明確指定一個 enum 的基礎類型。

public enum Foo : UInt32 {} // Invalid
public enum Bar : uint   {} // Valid

这只是一个问题,规格如何定义enum声明 - 结尾后的一部分必须是整体类型的生产,这是一个标志的sbyte, byte, short, ushort, int, uint, long, ulong, char......相反的类型的生产,用于变量声明,例如,它不表明任何其他差异。

至少有四种差异:

字符串是保留的单词,但字符串只是一个类名称,这意味着字符串本身不能作为变量名称使用。

2、你不能使用 String 而不“使用系统”。所以你用“string”写得更少。

3、“String”比“string”更好地命名公约,因为它是一种不变的类型。

“String”是大多数编辑器中突出的C#关键字和合成,但不是“String”。