문제

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