【问题标题】:Interfaces, structs and boxing is this code doing what I think?接口、结构和装箱,这段代码是按照我的想法做的吗?
【发布时间】: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 的分配如何工作? 我的看法:

  1. 在 Bar 构造函数中创建一个 Foo() 类型的结构并设置其 Foobar = 0;
  2. 使用装箱 (?) 强制转换为 IFoo 类型(因为 Biz 具有 IFoo 类型)
  3. 将引用类型IFoo拆箱为值类型结构(Foo)并赋值给tmp。

那么这个描述正确吗?即使我们不使用对象类,这真的是取消/装箱吗?

【问题讨论】:

  • 如果你用优化编译并用 ildasm 反编译,你看到拳击 IL 指令吗?
  • @cubrr 谢谢,这么明显的想法,但我没有想到。

标签: c# struct interface boxing


【解决方案1】:

您的描述是正确的。将struct 投射到接口会导致装箱。

一个有趣的副作用是分配给Bar.Biz.Foobar 不会引起任何变化:

var mybar = new Bar();
mybar.Biz.Foobar = 2;
int fooBar = mybar.Biz.Foobar; // still 0

可变的structs 是邪恶的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 2021-05-24
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多