2016-04-07 33 views
1

我正在写一些内存敏感的代码,其中由于各种原因,我必须包含一些值类型。此外,经过一些热身之后,我需要净新堆分配为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." 
+0

装箱不会将值类型(即int)设置为引用类型。您可以使用类来存储值类型并重用它。 – Eric

回答

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); 
    } 
}