2014-02-20 81 views
0

這是假設使用PictureBox的匹配遊戲,但我一直收到一個錯誤,無法將類型'object'隱式轉換爲'System.Drawing.Image'。而且我不知道如何從那裏繼續。如何使用數組和圖片框來顯示圖像

void Form1_Load(object sender, EventArgs e) 
{ 
    ArrayList images = new ArrayList(); 
    { 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG1.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG2.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG3.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG4.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG5.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG6.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG7.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG8.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG9.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG10.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG11.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG12.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG13.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG14.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG15.png")); 
     images.Add(Image.FromFile(Application.StartupPath + "\\MGG16.png")); 
    } 

    Random r = new Random(); 

    A1.Image = images[0]; 
} 
+1

請更新您的標題告訴人們你的問題是關於 – Liath

+0

什麼這是一個很好的用於循環的地方。 – semao

回答

4

您需要轉換對象:

A1.Image = images[0] as Image; 

這是因爲ArrayList是弱類型,這意味着images[i]將返回object。使用images[i] as Image進行投射會將此對象「轉向」其適當的類型,以便分配A1.Image = ...,該對象的期望類型爲Image的對象將起作用。

+4

也許發表一個解釋,讓OP瞭解他的錯誤? –

0

最好是使用強類型集合類似名單<〜>(也可用於循環添加圖像):

void Form1_Load(object sender, EventArgs e) 
{ 
    List<Image> images = new List<Image>(); 

    for (int i=1; i <= 16; i++) 
     images.Add(Image.FromFile(String.Format(@"{0}\MGG{1}.png",Application.StartupPath,i); 
    Random r = new Random();  
    A1.Image = images[r.Next(images.Count)]; 
} 
+0

但事情是我想隨機放置的圖像 – user3054895

+0

我編輯我的答案分配隨機圖像。 – semao

+0

圖像不出於某種原因 – user3054895

相關問題