2012-05-18 6 views
0

for 루프가 while 루프처럼 작동하도록하는 방법이 있다는 것을 알고 있습니다.`for` 루프와 같이`for` 루프를 만드는 방법은?

for (long Position = BR.BaseStream.Position; Position < BR.BaseStream.Length; //Don't Know This) 
{ 
    int BlockLength = BR.ReadInt32(); 
    byte[] Content = BR.ReadBytes(BlockLength); 
} 
+0

왜 그렇게하고 싶습니까? 왜 그 동안보기를 사용하지 않습니까? – Ramesh

+0

숙제 같은 냄새가납니다. – dwerner

+0

@dwerner 최근 과제는 숙제가 아닙니다! 사실 나는 모든 'while'루프를 for 루프로 전송하려고합니다. – Writwick

답변

4

사용 때마다 :이 있고, 지금까지이 while 루프에 대한 for 상응하는 필요

while (BR.BaseStream.Position < BR.BaseStream.Length) // BR = BinaryReader 
{ 
    int BlockLength = BR.ReadInt32(); 
    byte[] Content = BR.ReadBytes(BlockLength); 
} 

..

:

나는이 코드 작업을 Read 메소드 중 하나 인 BinaryReader는 위치를 증가시키기 때문에 실제로 해당 섹션에는 아무 것도 필요하지 않습니다.

for (long Position = BR.BaseStream.Position; Position < BR.BaseStream.Length; Position = BR.BaseStream.Position) 
{ 
    int BlockLength = BR.ReadInt32(); 
    byte[] Content = BR.ReadBytes(BlockLength); 
} 

업데이트 : 나는 그냥 Position 변수가 이제까지 업데이트 점점되지 않는다는 것을 깨달았다. for 루프의 끝이나 세 번째 섹션에서 업데이트 할 수 있습니다. for 루프의 세 번째 섹션에서 Position을 업데이트하는 코드를 업데이트했습니다.

+0

감사합니다. 방금 이것을 찾고있었습니다 !! – Writwick

+0

이것은 5 분 만에 답변입니다! – Writwick

3

당신이 그것을하고 싶은 이유를 잘 모르겠지만,이 루프에 대한 의사 코드에서

int i = 0; 
for (; true;) 
{ 
    Console.WriteLine(i); 
    if(++i==10) 
     break; 
} 
+0

C#은 null 문을 상속받습니다 ... – dwerner

+0

좋은 답변입니다! +1 – Writwick

0

처럼 보이게하는 방법이며,이 두 루프는 동일합니다

루프 1 :

Type t = initialiser; 
while (t.MeetsCondition()) 
{ 
    // Do whatever 
    t.GetNextValue(); 
} 

루프 2 :

for (Type t = initialiser; t.MeetsCondition(); t.GetNextValue()) 
    // Do whatever 

여기서 나머지를 해결할 수 있다고 생각합니다.

0
for (long Position = BR.BaseStream.Position; Position < BR.BaseStream.Length; /* If you Don't Know  This, dont specify this. It is Optionl and can be kept blank */) 
{ 
    int BlockLength = BR.ReadInt32(); 
    byte[] Content = BR.ReadBytes(BlockLength); 
} 
관련 문제