Mar*_*ell 93
Console.WriteLine(typeof(string).IsClass); // true
Run Code Online (Sandbox Code Playgroud)
这是一种参考类型.
它不能是数值类型,作为值类型需要的已知大小的堆栈等.作为参考类型,大小参考事先是已知的,即使所述字符串的大小是没有的.
它的行为就像你期望值类型一样,因为它是不可变的; 即它一旦创建就不会改变.但是还有很多其他不可变的引用类型.例如,委托实例.
*=除了内部StringBuilder
,但你在这样做的时候从未看到它...
Cha*_*ana 11
基本的"解释"基于"什么"实际存储在您为事物"声明"变量时分配的内存位置.如果事物的实际值存储在变量名称引用的内存位置,则它是值类型.
int x; // memory allocated to hold Value of x, default value assigned of zero
Run Code Online (Sandbox Code Playgroud)
如果,otoh,当您"声明"变量时分配的内存插槽将仅保存其中将存储实际值(或多个值)的其他内存地址,则它是引用类型.
MyClass x; // Memory allocated to hold an address,
// default address of null (0) assigned.
// NO MEMORY ALLOCATED for x itself
Run Code Online (Sandbox Code Playgroud)
或者,如果声明包括初始化,
MyClass x = new MyClass();
// Now, Memory slot (call it Addr1) is allocated to hold address of x,
// more memory (call it Addr2) is allocated to hold a new MyClass object.
// New MyClass object created, stored in memory Addr2 (on the Heap)
// Address of new object (Addr2) is stored in Addr1
Run Code Online (Sandbox Code Playgroud)
对于一个字符串,该字符串是在Heap上创建的,它的地址位于为该变量分配的内存槽中,因此它是一个引用类型.