zoukankan      html  css  js  c++  java
  • Enum Display Extension 转 武胜

    Enum Display Extension

    By jim lahey, 30 Oct 2011
      report
     
     

    In response to Adrian Cole's comment to the OP - due to living and working in a country where there are four official languages, plus English as a de facto fifth, I've encountered this before.

    Provided you have the corresponding .resx files embedded in the same assembly as the enum and your enum values correspond to the resource names in those files, you can do the following:

    Create a bog-standard enum without attributes:

    //standard enum
    public enum EmployeeType
    {
        Boss,
        AdministrativeAssistant,
        Janitor,
        StandardEmployee
    }

    And create an extension method that uses the enum value as the key for the .NET Framework to look up the appropriate language string:

    //Enum Extension class
    public static class EnumExtensions
    {
        //Gets the localized string representation of the enum value
        public static string ToLocalizedString(this Enum value)
        {
            var resourceManager = new ResourceManager(Type.GetType(
                string.Format("{0}.{1}Strings", 
                value.GetType().Namespace, value.GetType().Name)));
     
            var localizedString = resourceManager.GetString(value.ToString());
     
            return string.IsNullOrEmpty(localizedString) ? value.ToString() : localizedString;
        }
    }

    Then all you need to do to get a localized string in place of the enum value is:

    var localized = EmployeeType.Boss.ToLocalizedString();

    And for converting a localized string back to the enum, you call an extension method on the string:

    //string extension method
    public static T FromLocalizedString<T>(this string localizedString)
    {
       var t = typeof (T);
     
       var resourceType = Type.GetType(string.Format("{0}.{1}Strings", 
                                       t.Namespace, t.Name));
     
       var enumObject = resourceType.GetProperties()
           .Where(p => p.GetValue(null, null) != null && 
                  p.GetValue(null, null).ToString() == localizedString)
           .DefaultIfEmpty(null)
           .FirstOrDefault();
     
       return enumObject == null ? default(T) : (T)Enum.Parse(t, enumObject.Name);
    }

    like this:

    var boss = "Chef".FromLocalizedString<EmployeeType>();
  • 相关阅读:
    UNIX网络编程之旅配置unp.h头文件环境[ 转]
    C++著名程序库
    开源框架完美组合之Spring.NET + NHibernate + ASP.NET MVC + jQuery + easyUI 中英文双语言小型企业网站Demo
    网络库介绍
    置顶问题
    最近做的一个项目
    Storm 遇到问题?
    海量算法视频下载
    Quartz.NET作业调度框架详解
    c#中的委托、事件、Func、Predicate、Observer设计模式以及其他
  • 原文地址:https://www.cnblogs.com/zeroone/p/2709493.html
Copyright © 2011-2022 走看看