C# - Are Dynamic Parameters Boxed
If I have:
void Foo(dynamic X) {
}
And then:
Foo(12);
开发者_高级运维Would 12 get boxed? I can't imagine it would, I'd just like to ask the experts.
Yes, it will.
Under the hood, a dynamic
type is just an object
with some meta-data, so value-types will get boxed when put into a variable, field, or parameter of type dynamic
.
The method will actually be compiled as this:
void Foo([Dynamic] object X)
{
}
Read more about the DynamicAttribute here.
IL for code calling it:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 8
L_0000: nop
L_0001: ldc.i4.s 12
L_0003: box int32
L_0008: call void ConsoleApplication13.Program::Foo(object)
L_000d: nop
L_000e: ret
}
Yes. A value type needs to be boxed in order to type check.
Yes !
Since its a value type, it will be boxed.
精彩评论