2016-07-16 47 views
0

我一直在經歷一個二維數組,並想停止重複同樣的嵌套的循環如何DRY原則上適用於重複C#的for循環

for (int x = 0; x < width; x++) { 
    for (int y =0; y < height; y++) { 
    // Do some stuff 
    } 
} 

有沒有辦法來幹出嵌套的循環沿的

iterateThroughMatrix (doSomeStuff) 
iterateThroughMatrix (doSomethingElse) 
iterateThroughMatric (doSomeOtherStuff) 

void iterateThroughMatrix (doSomething) { 
    for (int x = 0; x < width; x++) { 
    for (int y =0; y < height; y++) { 
     // doSomething here 
    } 
    } 
} 
+0

看看[如何傳遞方法作爲參數](http://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp) –

回答

3

行更多的東西你需要的東西是這樣的:

void iterateThroughMatrix(Action<int, int> doSomething) 
{ 
    for (int x = 0; x < width; x++) 
    { 
     for (int y = 0; y < height; y++) 
     { 
      doSomething(x, y); 
     } 
    } 
} 

您可以使用任何具有兩個整數的代表,但Action<int, int>已內置並準備就緒。