开发者

To Experts: What's The Difference In This Code?

I ask this because I got an error "ArgumentOutOfRange" using the generic form.

  List<WaitHandle> arraywaithandles = new List<WaitHandle>(4);

or...

    WaitHandle[] A = new WaitHandle[4]

This works:

       for (int i = 0; i < 4; i++)
        {
            A[i] = (arrayresultados[i].AsyncWaitHandle);
        }

This does not work:

       for (int i = 0; i < 4; i++)
        {
            arraywaithandles[i]开发者_如何转开发 = (arrayresultados[i].AsyncWaitHandle);
        }


This:

new List<WaitHandle>(4);

creates a List object that has an initial capacity of 4 WaitHandles. What that means is that the List after the above line will hold zero WaitHandles, but has at least enough memory to receive 4 WaitHandles without having to perform an extra memory allocation later.

This way, if you know you will need to insert 200 WaitHandles but don't actually have them right now, you can have the List object allocate enough memory for 200 WaitHandles in one go instead of having to reallocate as you add WaitHandles.

That's why your first for loop threw an ArgumentOutOfRange exception because you tried to access non-existing WaitHandles in arraywaithandles. If you need to add WaitHandles to the List, then you would use the aptly named List<T>::Add() method.

This, on the other hand:

new WaitHandle[4];

creates an array of 4 WaitHandles that will be in existence by the time the above line finishes.


You want to try this instead:

for (int i = 0; i < 4; i++)
{
    arraywaithandles.Add(arrayresultados[i].AsyncWaitHandle);
}


try this

List<WaitHandle> arraywaithandles = 
    Enumerable.Repeat<WaitHandle>(null, 4).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜