如何List.Clear()来实现在C#中?来实现、List、Clear

由网友(月亮在偷笑)分享简介:我假设它使用一个数组来实现列表。如何 List.Clear()实施?其实是否清理数组或只是使这个列表中的新阵?公共类List {私人阵列_array;公共无效Clear1(){_array.length = 0;}公共无效Clear2(){_array =新的Array();}}解决方案 这样的(使用.net反射)...

我假设它使用一个数组来实现列表。如何 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实例。

Clear 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.

阅读全文

相关推荐

最新文章