How to convert a type specified to a object type in IL.
There are two kinds of type in the IL: value type and non-value type. It can be judged from the IsValueType property of a object type. e.g. typeof(String).IsValueType.
ValueType includes Int(16, 32, 63), float(Single), Double, and so on.
No-ValueType includes String, Custom-Class and so on.
When you convert a type specified to a object type, if the type specified is a valuetype, the unbox.any instruction is used, else the castclass instruction be used. Please look the sample as follow:
Valuetype
.method private hidebysig instance float32
TTT(object s) cil managed
{
// Code size 12 (0xc)
.maxstack 1
.locals init ([0] float32 CS$1$0000)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: unbox.any [mscorlib]System.Single
IL_0007: stloc.0
IL_0008: br.s IL_000a
IL_000a: ldloc.0
IL_000b: ret
} // end of method Form1::TTT
Non ValueType
.method private hidebysig instance string
PPP(object s) cil managed
{
// Code size 12 (0xc)
.maxstack 1
.locals init ([0] string CS$1$0000)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: castclass [mscorlib]System.String
IL_0007: stloc.0
IL_0008: br.s IL_000a
IL_000a: ldloc.0
IL_000b: ret
} // end of method Form1::PPP
浙公网安备 33010602011771号