代码之家  ›  专栏  ›  技术社区  ›  arynaq

临时值类型是如何装箱的

c#
  •  0
  • arynaq  · 技术社区  · 7 年前

    这也许是个奇怪的问题,但我想知道这是如何实现的。

    考虑下面的代码段(在这个代码段中,我出于任何原因决定在引用类型的数组中装箱,而不是仅仅创建T数组)

    public class HeapScatteredValueList<T> where T : struct
    {
        private object[] _list;
        private int _head;
    
        public HeapScatteredValueList(int maxCapacity)
        {
            _list = new object[maxCapacity];
        }
    
        public void Add(T item)
        {
            var newHead = _head + 1;
            if (newHead > _list.Length - 1)
            {
                throw new Exception();
            }
    
            _list[_head++] = item;
        } // The "item" that was copied in to the stack of this function should be destroyed here, what is in the list then?
    
        public T this[int index] => (T) _list[index];
    }
    

    现在每当我调用这个函数,因为 T Add(T item) 所以在这条线上 _list[_head++] = item object 在数组指向。。。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Chirag Rupani    7 年前

    .Net具有IL语句到框值类型- box box操作执行以下操作:

    1. 根据值类型的大小(加上其他字段-类型对象指针和同步块索引)分配内存
    2. 复制 这个新内存的值

    原始值类型与此引用没有关系。当它超出范围时,它将丢失,但引用将一直保留,直到它被垃圾回收。