【发布时间】:2015-11-06 02:08:30
【问题描述】:
我正在阅读这个答案:https://stackoverflow.com/a/15209464/1073672 这是代码,为了完整起见,复制了一些代码。
using System;
namespace Test
{
interface IFoo
{
int Foobar{get;set;}
}
struct Foo : IFoo
{
public int Foobar{ get; set; }
}
class Bar
{
// These two lines. I can not understand how they will work.
Foo tmp;
public IFoo Biz{ get { return tmp; } set { tmp = (Foo) value; } }
public Bar()
{
Biz = new Foo(){Foobar=0};
}
}
class MainClass
{
// This is not really important.
public static void Main (string[] args)
{
var mybar = new Bar();
}
}
}
Bar 的构造和对Biz 的分配如何工作?
我的看法:
- 在 Bar 构造函数中创建一个
Foo()类型的结构并设置其 Foobar = 0; - 使用装箱 (?) 强制转换为
IFoo类型(因为Biz具有IFoo类型) - 将引用类型
IFoo拆箱为值类型结构(Foo)并赋值给tmp。
那么这个描述正确吗?即使我们不使用对象类,这真的是取消/装箱吗?
【问题讨论】:
-
如果你用优化编译并用 ildasm 反编译,你看到拳击 IL 指令吗?
-
@cubrr 谢谢,这么明显的想法,但我没有想到。
标签: c# struct interface boxing