簡體   English   中英

如何一次從資源中檢索所有圖像?

[英]How can I retrieve all the images from Resources at once?

我已將一些圖像添加到項目的資源中,並且我想將它們添加到 Bitmap 列表中。
查看我的代碼,似乎效率很低:我必須重復相同的代碼 12 次。

如何一次性添加它們?

public partial class Form1 : Form
{
    private List<Bitmap> chineseZodiacList;

    public Form1()
    {
        InitializeComponent();
        chineseZodiacList.Add(Properties.Resources.猴);
        chineseZodiacList.Add(Properties.Resources.雞);
        chineseZodiacList.Add(Properties.Resources.狗);
        chineseZodiacList.Add(Properties.Resources.豬);
        chineseZodiacList.Add(Properties.Resources.鼠);
        chineseZodiacList.Add(Properties.Resources.牛);
        chineseZodiacList.Add(Properties.Resources.虎);
        chineseZodiacList.Add(Properties.Resources.兔);
        chineseZodiacList.Add(Properties.Resources.龍);
        chineseZodiacList.Add(Properties.Resources.蛇);
        chineseZodiacList.Add(Properties.Resources.馬);
        chineseZodiacList.Add(Properties.Resources.羊);
    }
}

一種簡單的方法是構建一個與 Bitmap 名稱對應的字符串列表,並將它們加載到一個 go 中。 在這里,使用您的List<Bitmap> ,但Dictionary<string, Bitmap> (如第二個片段所示)可能更好:

string[] zodiacSymbols = { "猴", "雞", "狗", "豬", "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊" };
List<Bitmap> zodiacImages = zodiacSymbols.Select(sym => (Bitmap)Properties.Resources.ResourceManager.GetObject(sym)).ToList();

或者,要獲取 Bitmap 類型的所有資源(如本例所示),您可以使用ResourceReader class 並填寫例如字典:

Dictionary<string, Bitmap> resImages = new Dictionary<string, Bitmap>();

其中包含 this 類型的所有資源以及用作 Key 的資源名稱:
(當然您也可以按名稱過濾 - 或其他任何內容 - 不僅僅是 ty 類型)

using System.Reflection;

var asm = Assembly.GetExecutingAssembly();

using (var asmResStream = asm.GetManifestResourceStream($"{asm.GetName().Name}.Properties.Resources.resources"))
using (var resReader = new ResourceReader(asmResStream)) {
    foreach (DictionaryEntry entry in resReader) {
        if (entry.Value.GetType() == typeof(Bitmap)) {
            resImages.Add((string)entry.Key, (Bitmap)entry.Value);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM