开发者

Creating a List<> of a Subset of Keys and Strings in a .RESX file

I have a .resx file that contains all the strings for my website. I'd like to create a List<string> of a subset of these strings without having to use add() for each new string like this:

List<string> listOfResourceStrings= new List<string>();
listOfResourceStrings.Add(Resources.WebSite_String1);
listOfResourceStrings.Add(Resources.WebSite_String2);
listOfResourceStrings.Add(Resources.WebSite_String3);
listOfResourceStrings.Add(Resources.WebSite_String4);
listOfResourceStrings.Add(Resources.WebSite_String5);
listOfResourceStrings.Add(Resources.WebSite_Stringn);

I could use...

System.Resources.ResourceSet listOfResourceStrings = Resources.ResourceManager.G开发者_如何学CetResourceSet(System.Threading.Thread.CurrentThread.CurrentCulture, true, true);

...but this returns a ResourceSet and contains all the strings. And, there doesn't seem to be an easy way to find a subset of the strings.

Thank you for your help,

Aaron


Resource data is stored in static properties, so reflection can be used to selectively extract the property values based on the property name.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;

namespace ConsoleApplication9
{
  public class Program
  {
    public static void Main(String[] args)
    {
      var strings = GetStringPropertyValuesFromType(typeof(Properties.Resources), @"^website_.*");
      foreach (var s in strings)
        Console.WriteLine(s);
    }

    public static List<String> GetStringPropertyValuesFromType(Type type, String propertyNameMask)
    {
      var result = new List<String>();
      var propertyInfos = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
      var regex = new Regex(propertyNameMask, RegexOptions.IgnoreCase | RegexOptions.Singleline);

      foreach (var propertyInfo in propertyInfos)
      {
        if (propertyInfo.CanRead &&
           (propertyInfo.PropertyType == typeof(String)) &&
           regex.IsMatch(propertyInfo.Name))
        {
          result.Add(propertyInfo.GetValue(type, null).ToString());
        }
      }

      return result;
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜