namespace BugQiang.Al { public class ClassA1 { public static readonly string STATIC_READONLY_STRING = "STATIC_READONLY_STRING"; public const string CONST_STRING = "CONST_STRING"; } }
using System; using BugQiang.Al; namespace BugQiang.B1 { public class ClassB1 { public static void ShowClassA1() { Console.WriteLine("ClassA1.CONST_STRING = {0} ClassA1.STATIC_READONLY_STRING = {1}", ClassA1.CONST_STRING, ClassA1.STATIC_READONLY_STRING); } } class Program { static void Main() { ClassB1.ShowClassA1(); } } }
编译并运行:
C:UsersdeDesktopao>csc /t:library /nologo ClassA1.cs
C:UsersdeDesktopao>csc /r:ClassA1.dll /nologo ClassB1.cs
C:UsersdeDesktopao>ClassB1
ClassA1.CONST_STRING = CONST_STRING
ClassA1.STATIC_READONLY_STRING = STATIC_READONLY_STRING
C:UsersdeDesktopao>
重新编辑ClassA1.cs
namespace BugQiang.Al { public class ClassA1 { public static readonly string STATIC_READONLY_STRING = "REBUILD_STATIC_READONLY_STRING"; public const string CONST_STRING = "REBUILD_CONST_STRING"; } }
重新编译ClassA1.cs,并运行ClassB1.exe:
C:UsersdeDesktopao>csc /t:library /nologo ClassA1.cs
C:UsersdeDesktopao>ClassB1
ClassA1.CONST_STRING = CONST_STRING
ClassA1.STATIC_READONLY_STRING = REBUILD_STATIC_READONLY_STRING
C:UsersdeDesktopao>
????
反编译打开ClassB1.exe
C:UsersdeDesktopao>ildasm
C:UsersdeDesktopao>
打开ClassB1.exe后,view/metainfo/show! (Ctrl + M)
在metainfo的最底部有这么一节:
User Strings
-------------------------------------------------------
70000001 : (64) L"ClassA1.CONST_STRING = {0}
ClassA1.STATIC_READONLY_STRING = {1}"
70000084 : (12) L"CONST_STRING"
以及ClassB1.ShowClassA1对应的IL代码
.method public hidebysig static void ShowClassA1() cil managed
{
// Code size 23 (0x17)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "ClassA1.CONST_STRING = {0}
ClassA1.STATIC_READONL"
+ "Y_STRING = {1}"
IL_0006: ldstr "CONST_STRING"
IL_000b: ldsfld string [ClassA1]BugQiang.Al.ClassA1::STATIC_READONLY_STRING
IL_0010: call void [mscorlib]System.Console::WriteLine(string,
object,
object)
IL_0015: nop
IL_0016: ret
} // end of method ClassB1::ShowClassA1
结束语:.NET字符串驻留机制