我想使用for循环按顺序访问具有不同但有序名称的资源。例如:
class Program
{
static void Main(string[] args)
{
ExtractImages();
}
static void ExtractImages()
{
Bitmap bmp;
for (int i = 0; i < 6; i++)
{
// Here I need something like:
// bmp = new Bitmap(Properties.Resources.bg + i);
bmp = new Bitmap(Properties.Resources.bg0); // in order bg0..bg5
bmp.Save("C:\\Users/Chance Leachman/Desktop/bg" + i + ".bmp");
}
}
}
有任何想法吗?基本上,它试图使String进入变量名。谢谢!
最佳答案
您可以使用ResourceManager.GetObject Method
GetObject方法用于检索非字符串资源。这些值包括属于原始数据类型(例如Int32或Double),位图(例如System.Drawing.Bitmap对象)或自定义序列化对象的值。通常,必须将返回的对象强制转换(在C#中)或转换(在Visual Basic中)为适当类型的对象。
var bitmap = Properties.Resources.ResourceManager.GetObject("bg0") as Bitmap;
在for循环中:
for (int i = 0; i < 6; i++)
{
string bitmapName = "bg" + i;
bmp = Properties.Resources.ResourceManager.GetObject(bitmapName) as Bitmap;
if(bmp != null)
bmp.Save("C:\\Users/Chance Leachman/Desktop/bg" + i + ".bmp");
}