如何重复使用盒子?

时间:2016-04-07 02:21:06

标签: c# .net value-type boxing

我正在写一些对内存敏感的代码,出于各种原因我必须选择一些值类型。此外,经过一些预热后,我需要净新堆分配为0.在我输入N值后,我的算法不再需要存储,但这些值必须经常更新。我希望能够重用已经在堆上创建的框。

以下代码表明盒子没有被重复使用(我可以想象为什么不这样做)。是否有不同的技术可以重复使用每个盒子?

using System;

public class Program
{
    public static void Main()
    {
        object x = 42;
        object y = x;
        x = 43;
        bool isSameBox = Object.ReferenceEquals(x, y);
        Console.WriteLine("Same box? {0}.", isSameBox);
    }
}

// Output: "Same box? False."

1 个答案:

答案 0 :(得分:0)

我的解决方案是将显式引用类型引入可重用框。

public class ReusableBox<T> where T : struct
{
    public T Value { get; set; }

    public ReusableBox()
    {

    }

    public ReusableBox(T value)
    {
        this.Value = value;
    }

    public static implicit operator T(ReusableBox<T> box)
    {
        return box.Value;
    }

    public static implicit operator ReusableBox<T>(T value)
    {
        return new ReusableBox<T>(value);
    }
}