2016-06-29 63 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);