这是我最终在单独的程序集中找到的解决方案(在我的情况下称为“ 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无法提供任何可用于此类常规任务的有用信息的情况,我甚至不满意。



