2016-06-29 64 views
0

如果我有一些資源,例如card1.png,card2.png等, 我想將它們加載到一個picBox,但只有正確加載圖像 例如,像從Visual C#中的資源加載圖像,使用字符串?

int cardNum = rn.Next(0,cardMax); 
picCard.Image = Properties.Resources."card"+cardNum+".png"; 

顯然,這不工作,但我怎麼會做什麼,我試圖做(建設資源名稱轉換成字符串後加載正確的資源)

+1

的可能的複製[如何通過字符串值從.NET資源得到名稱(RESX)文件(http://stackoverflow.com/questions/16361685/how-to-get-name-by-string-value-from-a-net-resource-resx-file) –

+1

@AndyKorneyev這是關於通過匹配內容而不是按名稱加載來查找資源的密鑰。 – Richard

+0

打開Resources.Designer.resx,你會看到它們是如何按字符串名稱查找的。 – Nyerguds

回答

0

嘗試使用:

var rm = new System.Resources.ResourceManager(((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly()).GetName().Name + ".Properties.Resources", ((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly())); 
Image img = (Bitmap)rm.GetObject("resourcesimagename.jpg"); 
0

取而代之的產生在Resources d類屬性使用ResourceManager直接:

string resName = $"card{cardNum}.png"; // Check the correct name in the .resx file. By using the wizards the extension is omitted, for example. 
picCard.Image = (Image)Properties.Resources.ResourceManager.GetObject(resName);