Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将PNG从资源加载到Picturebox(使用随机整数生成器)_C#_Image_Resources_Png_Picturebox - Fatal编程技术网

C# 将PNG从资源加载到Picturebox(使用随机整数生成器)

C# 将PNG从资源加载到Picturebox(使用随机整数生成器),c#,image,resources,png,picturebox,C#,Image,Resources,Png,Picturebox,我在参考资料中有大约600幅图像,格式如下: int num = rand.Next(0, 600); pictureBox1.Image = (Image)Properties.Resources.poke__**num**_; poke 1.png poke 2.png poke 3.png 等等 下面是我正在处理的代码示例: pictureBox1.Image = (Image)Properties.Resources.poke__1_; 这行代码用于加载第一个图像,如poke 1.p

我在参考资料中有大约600幅图像,格式如下:

int num = rand.Next(0, 600);
pictureBox1.Image = (Image)Properties.Resources.poke__**num**_;
poke 1.png

poke 2.png

poke 3.png

等等

下面是我正在处理的代码示例:

pictureBox1.Image = (Image)Properties.Resources.poke__1_;
这行代码用于加载第一个图像,如poke 1.png

但我希望能够加载这样的随机图像:

int num = rand.Next(0, 600);
pictureBox1.Image = (Image)Properties.Resources.poke__**num**_;
但是没有办法在资源名称中插入一个变量;我能做些什么来解决这个问题?

您可以做:

string name;

// Generate the random name.

pictureBox1.Image = (System.Drawing.Image)Properties.Resources.ResourceManager.GetObject(name, Properties.Resources.Culture);
此外,为了提高内存性能,您可能希望处置旧映像:

using (pictureBox1.Image)
{
    pictureBox1.Image = (System.Drawing.Image)Properties.Resources.ResourceManager.GetObject(name, Properties.Resources.Culture);
}
在这里,您必须使用原始文件名{0}.png,而不是静态属性名,其中的属性名被替换为下划线

当然,在从静态资源管理器属性获取图像时,会丢失编译时类型检查

更新

如果不想硬编码精确数量的图像属性,可以在属性中对所有图像值静态属性使用反射和查询。名称与模式匹配的资源,如下所示:

public static class ResourceHelper
{
    public static PropertyInfo [] GetStaticPropertiesOfType<TValue>(Type type)
    {
        return type
          .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
          .Where(p => typeof(TValue).IsAssignableFrom(p.PropertyType) && p.GetIndexParameters().Length == 0 && p.GetGetMethod(true) != null)
          .ToArray();
    }
}
然后,在你的课堂上:

        var regex = new Regex(@"^poke__\d+_$");
        var propertyDictionary = ResourceHelper.GetStaticPropertiesOfType<Image>(typeof(Properties.Resources)).Where(p => regex.IsMatch(p.Name)).ToDictionary(p => p.Name);
        foreach (var property in propertyDictionary.Values)
        {
            pictureBox1.Image = (Image)property.GetValue(null, null);
        }

在这里,您应该使用损坏的名称poke_{0},其中替换了无效的属性字符。

int num=1;字符串名称=poke__;+num+;;然后你排起长队,什么都没发生,图像也没有load@Will-确保您实际拥有该命名资源;如果这样做,Properties.Resources.poke_uuu1将作为静态属性存在。@will-answer-updated。但不能重现你的问题。