LoginSignup
1
0

More than 5 years have passed since last update.

VisualStudioのプロジェクトリソースを使いやすく列挙する

Last updated at Posted at 2017-10-13

VisualStudioのプロジェクトで
スクリーンショット (63).png

こういうPropertiesから設定できるリソースにアクセスする場合、

test.cs
var bitmap = Properties.Resources.add_user ;

とできるようなアクセスクラスが作成されてるのでどのプロパティを使えばいいかわかっている場合は非常に簡単になった。

ところが、これらをまとめて扱いたい場合はやっぱりLinqが使えたほうがありがたいのでどうしたもんかと。

リフレクション使ってぶん回す

    //リフレクションを使ってBitmap型のリソースを取得
var t = typeof(Properties.Resources);
foreach (var p in t.GetProperties(BindingFlags.Public | BindingFlags.NonPublic |BindingFlags.Static)) {
    if (p.PropertyType == typeof(Bitmap)) {
        //いろいろする
    }
}

これでも動作はするんだけど自前で定義済みのリストをリフレクション経由で読み込むとかクソダサい。

ResourceSetを使う

foreach (var b in Properties.Resources.ResourceManager
    .GetResourceSet(System.Threading.Thread.CurrentThread.CurrentCulture,true,true)
    .OfType<DictionaryEntry>()
    .Where(e=>e.Value is Bitmap)) {
    //いろいろする
}

リフレクションよりマシだけど結局取れたのがDictionaryEntry(string)b.Keyみたいにキャスト不可避なのがダサい。

無理やり最適化

ResourceManagerExtender.cs

public static class ResourceManagerExtender {
    public static IEnumerable<KeyValuePair<string,T>> getEntries<T>(this ResourceManager rman) {
        return rman.GetResourceSet(System.Threading.Thread.CurrentThread.CurrentCulture, true, true)
            .OfType<DictionaryEntry>()
            .Where(e => e.Value is T)
            .Select(e => new KeyValuePair<string, T>((string)e.Key, (T)e.Value));

    }
}

こうして

foreach (var b in Properties.Resources.ResourceManager.getEntries<Bitmap>()) {
    list.Images.Add(b.Key, b.Value);
}

こうじゃ。

結局

スマートじゃない。
リソース周りってあんまりブラッシュアップされてない雰囲気ある。

参考

ResourceManager クラス (System.Resources)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0