C# 如何从字符串转换为变量名?

C# 如何从字符串转换为变量名?,c#,resources,C#,Resources,我希望使用for循环访问具有不同但有序名称的资源。例如: class Program { static void Main(string[] args) { ExtractImages(); } static void ExtractImages() { Bitmap bmp; for (int i = 0; i < 6; i++) { // Her

我希望使用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");
        }
    }
}
类程序
{
静态void Main(字符串[]参数)
{     
提取图像();
}
静态void ExtractImages()
{
位图bmp;
对于(int i=0;i<6;i++)
{
//在这里,我需要像这样的东西:
//bmp=新位图(Properties.Resources.bg+i);
bmp=新位图(Properties.Resources.bg0);//顺序为bg0..bg5
bmp.Save(“C:\\Users/Chance-Leachman/Desktop/bg”+i+”.bmp”);
}
}
}
有什么想法吗?它基本上是让一个字符串指向一个变量名。谢谢

您可以使用

GetObject方法用于检索非字符串资源。这些值包括属于基本数据类型(如Int32或Double)、位图(如System.Drawing.Bitmap对象)或自定义序列化对象的值。通常,返回的对象必须强制转换(在C#中)或转换(在Visual Basic中)为适当类型的对象

在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");
}
for(int i=0;i<6;i++)
{
字符串bitmapName=“bg”+i;
bmp=Properties.Resources.ResourceManager.GetObject(bitmapName)作为位图;
如果(bmp!=null)
bmp.Save(“C:\\Users/Chance-Leachman/Desktop/bg”+i+”.bmp”);
}
您可以使用

GetObject方法用于检索非字符串资源。这些值包括属于基本数据类型(如Int32或Double)、位图(如System.Drawing.Bitmap对象)或自定义序列化对象的值。通常,返回的对象必须强制转换(在C#中)或转换(在Visual Basic中)为适当类型的对象

在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");
}
for(int i=0;i<6;i++)
{
字符串bitmapName=“bg”+i;
bmp=Properties.Resources.ResourceManager.GetObject(bitmapName)作为位图;
如果(bmp!=null)
bmp.Save(“C:\\Users/Chance-Leachman/Desktop/bg”+i+”.bmp”);
}