gpt4 book ai didi

c# - 如何从字符串转到变量名称?

转载 作者:太空宇宙 更新时间:2023-11-03 19:09:22 26 4
gpt4 key购买 nike

我想使用 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

The GetObject method is used to retrieve non-string resources. These include values that belong to primitive data types such as Int32 or Double, bitmaps (such as a System.Drawing.Bitmap object), or custom serialized objects. Typically, the returned object must be cast (in C#) or converted (in Visual Basic) to an object of the appropriate type.

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");
}

关于c# - 如何从字符串转到变量名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22108714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com