如何List.Clear()来实现在C#中? [英] How is List.Clear() implemented in C#?

查看:666
本文介绍了如何List.Clear()来实现在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我假设它使用一个数组来实现列表。如何 List.Clear()实施? 其实是否清理数组或只是使这个列表中的新阵?

 公共类List {

    私人阵列_array;

    公共无效Clear1(){
        _array.length = 0;
    }
    公共无效Clear2(){
        _array =新的Array();
    }
}
 

解决方案

这样的(使用.net反射):

 公共无效清除()
{
    如果(this._size大于0)
    {
        Array.Clear(this._items,0,this._size);
        this._size = 0;
    }
    this._version ++;
}
 

正如你看到的,它只是清除了同一阵列。它可能是假设,如果你重复使用相同的列表,你可能会想用数据大致相同数量填充它。如果你要释放的数组,你需要创建一个新的List实例。

I assume it uses an array to implement List. How is List.Clear() implemented? Does it actually clean up the array or just make a new array for this list?

public class List {

    private Array _array;

    public void Clear1 () {
        _array.length = 0;
    }
    public void Clear2 () {
        _array = new Array();
    }
}

解决方案

Like this (using .NET Reflector):

public void Clear()
{
    if (this._size > 0)
    {
        Array.Clear(this._items, 0, this._size);
        this._size = 0;
    }
    this._version++;
}

As you see, it just clears the same array. It probably assumes that if you're reusing the same list, you'll probably want to refill it with roughly the same amount of data. If you want to release the array, you'll need to create a new List instance.

这篇关于如何List.Clear()来实现在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆