栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

DisplayNameAttribute的本地化

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

DisplayNameAttribute的本地化

这是我最终在单独的程序集中找到的解决方案(在我的情况下称为“ Common”):

   [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)]   public class DisplayNameLocalizedAttribute : DisplayNameAttribute   {      public DisplayNameLocalizedAttribute(Type resourceManagerProvider, string resourceKey)         : base(Utils.LookupResource(resourceManagerProvider, resourceKey))      {      }   }

用代码查找资源:

  internal static string LookupResource(Type resourceManagerProvider, string resourceKey)  {     foreach (PropertyInfo staticProperty in  resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic))     {        if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager))        {System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);return resourceManager.GetString(resourceKey);        }     }     return resourceKey; // Fallback with the key name  }

典型用法是:

class Foo{      [Common.DisplayNameLocalized(typeof(Resources.Resource), "CreationDateDisplayName"),      Common.DescriptionLocalized(typeof(Resources.Resource), "CreationDateDescription")]      public DateTime CreationDate      {         get;         set;      }}

当我使用文字字符串作为资源键时,这非常难看。使用常量将意味着修改Resources.Designer.cs,这可能不是一个好主意。

结论:我对此感到不满意,但对于Microsoft无法提供任何可用于此类常规任务的有用信息的情况,我甚至不满意。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484009.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号