这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
当前回答
上述的一切基本上是正确的,一个人可以检查它。
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:当呼叫会员时,他们更喜欢线条)。
其他回答
晚到派对:我使用CLR类型百分之百的时间(好,除非被迫使用C#类型,但我不记得最后一次是什么时候)。
我起初在几年前开始做这件事,就像Ritchie的CLR书一样,这对我来说是有意义的,所有的CLR语言最终必须能够支持CLR类型,所以使用CLR类型自己提供了更清晰、可能更“可用”的代码。
现在我已经做了多年,这是一个习惯,我喜欢VS为CLR类型的颜色。
唯一真正的下载器是,自动完成使用C#类型,所以我最终重新编写自动生成的类型来指定CLR类型。
此外,现在,当我看到“int”或“string”,它似乎对我来说是真的错误的,就像我看到了1970年代的C代码一样。
这是一个协议问题,真的. 字符串只是看起来更像C/C++风格. 通用协议是使用你所选择的语言提供的任何缩写(int/Int为Int32)。 这也适用于“对象”和十数。
理论上,这可能有助于将代码转移到某些未来的64位标准,其中“int”可能意味着Int64,但这不是问题,我会期望任何升级巫师将改变任何int引用到Int32无论如何只是安全。
上述的一切基本上是正确的,一个人可以检查它。
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:当呼叫会员时,他们更喜欢线条)。
如果有用的是真正看到没有线和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 ]
您不需要进口名称空间(使用系统;)来使用字符串,因为它是一个全球的名称 System.String。
要了解更多关于 Alias 的信息,您可以查看此链接。