c# - 本地化枚举描述属性

标签 c# .net localization enums

在 .net 中本地化枚举描述的最佳方法是什么?

(枚举描述示例参见 Adding descriptions to enumeration constants)

理想情况下,我想要使用 ResourceManager 和资源文件的东西,以便它适合应用程序其他区域的本地化方式。

最佳答案

这就是我最终要做的,我没有看到添加自定义属性类来保存资源键然后查找资源文件的值(value) - 为什么不直接使用枚举类型名 + 值作为资源 key ?

using System;
using System.Resources;
using System.Reflection;

public class MyClass
{
  enum SomeEnum {Small,Large};

  private ResourceManager _resources = new ResourceManager("MyClass.myResources",
                          System.Reflection.Assembly.GetExecutingAssembly());    

  public string EnumDescription(Enum enumerator)
  {     
    string rk = String.Format("{0}.{1}",enumerator.GetType(),enumerator);
    string localizedDescription = _resources.GetString(rk);

    if (localizedDescription == null)
       {
       // A localized string was not found so you can either just return
       // the enums value - most likely readable and a good fallback.
       return enumerator.ToString();

       // Or you can return the full resourceKey which will be helpful when
       // editing the resource files(e.g. MyClass+SomeEnum.Small) 
       // return resourceKey;
       }
    else
       return localizedDescription;
    }


  void SomeRoutine()
  {
    // Looks in resource file for a string matching the key
    // "MyClass+SomeEnum.Large"
    string s1 = EnumDescription(SomeEnum.Large);       
  }
}

关于c# - 本地化枚举描述属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/569298/

相关文章:

c# - 在 .NET Core 中使用 MVC 之外的 Razor

C# - 使用 Int 与 Long 的相同计算速度更慢?

php - Laravel Blade @lang() 本地化中的多元化?

ios - 阿拉伯语翻译在 iOS 9 上不工作,但在 iOS 10 上工作

localization - 通过 Typoscript 添加对 TYPO3 扩展的翻译

c# - BrokeredMessage 在等待后被处置

c# - 尝试发送电子邮件时如何捕获/报告 elmah 命中的错误?

c# - 如何添加 net5.0 Worker 应用程序 AddJsonOptions

c# - 文件流、锁定和序列化

c# - Ninject 绑定(bind)不同的实现