NET问答: String 和 string 到底有什么区别?

咨询区

  • Peter O.

开门见山,参考如下例子:

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

请问这两者有什么区别,在实际使用上要注意一些什么?.

回答区

  • Derek Park

string  是 C# 中 System.String 的别名,从技术角度上来说,他们没有任何区别,就好像 int 和 System.Int32 一样。

至于使用上要注意什么?我通常推荐使用编译器内置的关键词 string,比如说:

string place = "world";

同样的,如果你想使用 string 下的某些方法,我推荐使用类方式 String.Format ,比如:

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

点评区

其实要想看两者的区别,可以先看看他们的 IL 是否一致?如果一致,那就看看汇编是否一致?沿着这个思路可以写个例子:

        static void Main(string[] args)
        {
            string s = "Hello world!";
            String s2 = "Hello world!";
        }

然后用 ILSpy 输出 IL 指令。

.method private hidebysig static 
 void Main (
  string[] args
 ) cil managed 
{
 // Method begins at RVA 0x2050
 // Code size 14 (0xe)
 .maxstack 1
 .entrypoint
 .locals init (
  [0] string s,
  [1] string s2
 )

 IL_0000: nop
 IL_0001: ldstr "Hello world!"
 IL_0006: stloc.0
 IL_0007: ldstr "Hello world!"
 IL_000c: stloc.1
 IL_000d: ret
} // end of method Program::Main

从上面可以看出,都是用 ldstr 指令从元数据中提取新对象的引用,参考官方解释:

NET问答: String 和 string 到底有什么区别?

那怎么查看元数据中的 Hello world 字面量呢?可以用 PPEE 工具。

NET问答: String 和 string 到底有什么区别?