質問

I have a list with a specified initial capacity:

private void Foo()
{
    List<double> myList = new List<double>(1024);
    myList.Add(1.0);
    myList.Add(2.0);
    ....

    myList.Clear(); <-- what is the list's 'initial' capacity now?
}

What will be myList's capacity after calling myList.Reset()? Is it 1024?

役に立ちましたか?

解決

According to the documentation:

Capacity remains unchanged. To reset the capacity of the List, call the TrimExcess method or set the Capacity property directly. Decreasing the capacity reallocates memory and copies all the elements in the List. Trimming an empty List sets the capacity of the List to the default capacity.

Of course you can confirm this for yourself simply by setting a breakpoint and checking the value of the Capacity property before and after you call Clear.

There is no Reset method (unless you're referring to some extension method), but the documentation quoted above indicates you can reset the capacity by calling TrimExcess.

他のヒント

List<double> myList = new List<double>(1024);
Console.WriteLine(myList.Capacity);
myList.Add(1.0);
myList.Add(2.0);
Console.WriteLine(myList.Capacity);
myList.Clear();
Console.WriteLine(myList.Capacity);

Capacity remains unchanged. To reset the capacity of the List, call the TrimExcess method or set the Capacity property directly. Decreasing the capacity reallocates memory and copies all the elements in the List. Trimming an empty List sets the capacity of the List to the default capacity.

See here: http://msdn.microsoft.com/en-us/library/dwb5h52a%28v=vs.110%29.aspx

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top