【问题标题】:Do I need to release memory used by arrays in C#?我需要释放 C# 中数组使用的内存吗?
【发布时间】:2013-08-01 11:20:17
【问题描述】:

假设我有一个类型为 InvoiceItem 的对象数组,定义如下:

 private class InvoiceItem
    {
        public DateTime InvoiceDate { get; set; }
        public int InvoiceID { get; set; }
        public byte ItemType { get; set; }
        public short Quantity { get; set; }
        public string ProductName { get; set; }
        public decimal Price { get; set; }
        public decimal Amount{ get; set; }

        public InvoiceItem(DateTime InvoiceDate,int InvoiceID, short Quantity, string ProductName, decimal Price,decimal Amount, byte ItemType)
        {
            this.InvoiceDate = InvoiceDate;
            this.InvoiceID = InvoiceID;
            this.Quantity = Quantity;
            this.ProductName = ProductName;
            this.Price = Price;
            this.Amount = Amount;
            this.ItemType = ItemType;
        }
    }

我尝试将我的项目缓存在一个名为invoiceItemsCache的数组中

private InvoiceItem[] invoiceItemsCache;

每次我想刷新我的缓存时,我都会重新初始化我的数组:

invoiceItemsCache = new InvoiceItem[count];

我需要做一些事情释放之前缓存使用的内存,还是自动完成?如果有人提供一些有关在 C# 中存储和发布数组的方式的额外信息,我将不胜感激,以便消除我遇到的任何疑问和困惑。

【问题讨论】:

    标签: c# arrays memory-management


    【解决方案1】:

    C# 中的 GC 正在遍历对象并检查引用。如果一个对象没有引用它,则 GC 释放它。

    在你的情况下,如果你这样做

    invoiceItemsCache = new InvoiceItem[count];
    

    那么旧值没有引用它们(除非你对它们有不同的引用但你没有提到,然后你应该先处理它们)并将被释放

    【讨论】:

    • 也许他应该“处理掉一些参考资料”,但肯定不是Dispose() 他们。单词的选择很棘手。
    【解决方案2】:

    这是由底层垃圾收集器自动完成的。

    数组的存储和释放与 C# 中的任何其他对象一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 2014-08-05
      • 2012-06-11
      • 2012-04-17
      相关资源
      最近更新 更多