2016-07-19 13 views
-2

我正在使用visual studio community 2015製作一個基於表單的程序,該程序可以擲出兩個骰子。我需要根據我得到的隨機數字更改圖片。生成方法使用循環調用c#

我能做到這一點的方法是:

Random num = new Random(); 
int dice = num.Next(1,7); 

if (dice == 1)  { 
    pictureBox.Image = proj08.Properties.Resources._1; 
} else if (dice == 2) { 
    pictureBox.Image = proj08.Properties.Resources._2; 
} else if (dice == 3) { 
    pictureBox.Image = proj08.Properties.Resources._3; 
} else if (dice == 4) { 
    pictureBox.Image = proj08.Properties.Resources._4; 
} else if (dice == 5) { 
    pictureBox.Image = proj08.Properties.Resources._5; 
} else if (dice == 6) { 
    pictureBox.Image = proj08.Properties.Resources._6; } 

這工作完全並執行正是我想要的,但它是非常混亂的代碼。我想通過做這樣的事情來清理它:

Random num = new Random(); 
int dice = num.Next(1,7); 
pictureBox.Image = proj08.Properties.Resources._dice; 

但這不起作用。 我也想使用相同的代碼,即使pictureBox是pictureBox1或pictureBox2,這樣我就可以將它用於任何一個骰子。

+0

這個問題是關於引用資源,而不是關於骰子。至少將它標記爲更適合的東西的副本如下所示:http://stackoverflow.com/questions/1190729/vb-net-dynamically-select-image-from-my-resources – Crowcoder

回答

0

你可以有圖像的列表:

List<Image> images = new List<Image>() 
{ 
    proj08.Properties.Resources._1, 
    proj08.Properties.Resources._2, 
    proj08.Properties.Resources._3, 
    proj08.Properties.Resources._4, 
    proj08.Properties.Resources._5, 
    proj08.Properties.Resources._6 
}; 

Random num = new Random(); 
int dice = num.Next(1, images.Count + 1); 
pictureBox.Image = images[dice - 1]; // list starts from 0 

這是最直接的優雅的方式,我能想到的。

對於多個圖片框,您可以創建一個方法將圖片框作爲參數傳遞並將其圖片屬性設置爲參數。