2010-01-11 4 views

답변

2

배열의 각 항목을 반복하려면 foreach 구문을 사용하고 각 반복마다 카운터를 증가시킵니다. 이 같은

뭔가 : 여기

object[] o_arr = new object[5]; 

// code to initialise array 

int i = 0; 
foreach(object o in o_arr) 
{ 
    i++; 
} 

Console.WriteLine(i); 
+0

나는 이것을 위해 가능한 다른 방법을 좋아한다. – ratty

0

길이 속성을 올바르게 사용할 수 있습니까? Linq 네임 스페이스를 사용한다면 Count() 확장 메소드를 사용할 수 있습니다.

+0

OP는 말했다 : "길이 속성을 사용하지 않고" – xryl669

0

카운터를 사용하여 반복하지만 indexoutofbounds 예외가 발생하면 잡으십시오.하지만 그 이유는 무엇입니까?

1

는 "다른"솔루션입니다. :)

사용법 :

byte[] data = new byte[100]; 
int length = GetLength(data); 

구현 :

private static int GetLength(Array array) 
{ 
    if (array == null) 
     throw new ArgumentNullException("array"); 
    if (!array.GetType().FullName.EndsWith("[]")) 
     throw new ArgumentException("'array' must be an szarray."); 

    GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned); 
    try 
    { 
     IntPtr ptr = handle.AddrOfPinnedObject(); 
     int offsetToArrayLength = -8; 
     int length = (int)Marshal.PtrToStructure(new IntPtr(ptr.ToInt64() + offsetToArrayLength), typeof(int)); 
     return length; 
    } 
    finally 
    { 
     handle.Free(); 
    } 
} 
관련 문제