string是值类型,但为什么有的地方表现出的是引用类型的特征呢?
有个问题一直没搞清楚
string是值类型,但为什么有的地方表现出的是引用类型的特征呢?
我举个例子
using System;
class Program
{
static void Main(string[] args)
{
int i = 10;
string s = "abc";
object o = i;
o = s;
}
}
这段代码就能说明问题
i是值类型,这个毋庸置疑,i赋给o肯定要box一次,值类型的特性
按理说s赋给o也要box一次,也是值类型的特性
但是,请看下面的il代码
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// 代码大小 19 (0x13)
.maxstack 1
.locals init ([0] int32 i,
[1] string s,
[2] object o)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldstr "abc"
IL_0008: stloc.1
IL_0009: ldloc.0
IL_000a: box [mscorlib]System.Int32
IL_000f: stloc.2
IL_0010: ldloc.1
IL_0011: stloc.2
IL_0012: ret
} // end of method Program::Main
i已经box了,这是对的,但是s却没有,为什么?迷惑呀