2012-05-05 35 views
1

我使用C#XNA創建遊戲。
我有存儲在int[,]陣列像這樣的tilemap的:如何在方法內返回int [,]?

int[,] Map = 
    { 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
    }; 

我對我怎麼能在我的類的構造函數,甚至在可能的話方法接受這種類型的數組Map[,]和返回數組好奇?

我想返回一個int[,]就像這樣:

public int[,] GetMap() 
    { 
     return 
    int[,] Map1 = 
    { 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
    };; 
    } 
+10

你試過了嗎?你嘗試了什麼?錯誤是什麼? –

+0

閱讀此:http://msdn.microsoft.com/en-us/library/1h3swy84.aspx – Euphoric

回答

2

我想你想要這樣的:

public int[,] GetMap() 
{ 
    return new [,] 
    { 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
    }; 
} 

也可以是:

public int[,] GetMap() 
{ 
    int [,] map = new [,] 
    { 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
    }; 

    return map; 
} 
+0

謝謝,這就是我一直在尋找的東西。 – user1376460

1
void Method(int[,] map) 
{ 
    // use map here 
} 

int[,] MethodWithReturn() 
{ 
    // create Map here 
    return Map; 
} 
+0

我怎麼能返回數組? – user1376460

+0

@ user1376460錯誤......你有沒有試過'返回地圖;'?你有什麼嘗試,你有什麼問題?請發佈您的代碼和您收到的錯誤消息。 –

+0

你可能誤解了我的問題。 – user1376460

0
public int[,] GetMap() 
{ 
    int[,] map = new int[,] 
    { 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
     {1, 1, 1, 1, 1, 1, 1, 1 }, 
    }; 

    return map; 
} 

不能對多維數組使用隱式聲明,因此需要先聲明數組,然後返回它。

+0

這是純粹的錯誤。你可以馬上歸還。 – SimpleVar

+0

也許你是對的。我知道你不能以這種方式使用var,但也許可以返回。 – Chris

+0

你不必相信我。只要測試一下,看看自己。 – SimpleVar

0

你可以做確實:

return new int[,] 
      { 
       {1, 1, 1, 1, 1, 1, 1, 1}, 
       {1, 1, 1, 1, 1, 1, 1, 1}, 
       {1, 1, 1, 1, 1, 1, 1, 1} 
      }; 

但如果你問你會如何處理INT [,]從外面,當你不知道界限...然後:

從外部
private static int[,] CreateMap(out int height) 
{ 
    height = 3; 

    return new int[,] 
       { 
        {1, 1, 1, 1, 1, 1, 1, 1}, 
        {1, 1, 1, 1, 1, 1, 1, 1}, 
        {1, 1, 1, 1, 1, 1, 1, 1} 
       }; 
} 

用法:

int height; 
int[,] map = CreateMap(out height); 

int width = map.Length/height; 

for (int i = 0; i < height; i++) 
{ 
    for (int j = 0; j < width; j++) 
    { 
     Console.WriteLine(map[i, j]); 
    } 
}