【问题标题】:How to get Resources Key string value by passing only the Resources.MyProperty property如何通过仅传递 Resources.MyProperty 属性来获取资源键字符串值
【发布时间】:2018-08-16 12:26:22
【问题描述】:

我有一个标准资源文件,其中自动生成的源代码会生成这种类型的行:

/// <summary>
///   Looks up a localized string similar to Database Error.
/// </summary>
internal static string DatabaseError {
    get {
        return ResourceManager.GetString("DatabaseError", resourceCulture);
    }
}

/// <summary>
///   Looks up a localized string similar to Invalid Login.
/// </summary>
internal static string InvalidLogin {
    get {
        return ResourceManager.GetString("InvalidLogin", resourceCulture);
    }
}

我有一个地方循环遍历所有资源文件并获取所有条目的键和值并将它们存储在数据库中。 我有这个是因为翻译将由客户维护,而不需要每次有人想要重命名一个值或仅仅因为系统提供一种新语言时都制作新版本。

现在,我需要轻松访问这些翻译,我不想使用选项 1,而是使用选项 2(在这一行中,我使用资源属性而不是字符串)。

选项 1 // 我不想使用的那个

var txt= translationService.GetTranslation("DatabaseError", UserContext.LanguageId);

选项 2 // 我尝试使用的解决方案类型

var txt= translationService.GetTranslation(Resources.DatabaseError, UserContext.LanguageId);

选项 2 的“风格”,允许程序员不关心字符串。字符串容易出现错误/错误,并且通过使用现有属性,编译器可以知道某些内容何时不再有效。

问题在于,通过访问此属性,我从资源文件中获取了“已翻译”值....而且我只是不想尝试将此文本与现有资源键匹配...不仅因为这效率不高,但也不能确保不重复的值....

另一种解决方案,但我真的不想使用的是:创建我自己的“ResourcesClassMapping 类”,将“字符串”值保留在那里并进行此映射....我只是不想跟踪字符串键值,以了解它们是新旧的还是更新的。

我怎样才能以漂亮优雅的方式做到这一点?

【问题讨论】:

    标签: c# resources globalization


    【解决方案1】:

    好吧,在我等待一些反馈和可能的其他解决方案/方法的同时,我找到了一个不错的选择:

    public static string GetTranslation(Expression<Func<string>> expr)
    {
        if (!(expr.Body is MemberExpression member)) return "";
        var property = member.Member as PropertyInfo;
        if (property == null) return "";
    
        var key = property.Name;
    
        // TODO: using the key name I can get the value from the DB/cache
        var finalTranslation = ""; 
    
        return finalTranslation;
    }
    
    //and I call it like this:
    var txt = GetTranslation(() => Resources.Resources.InvalidLogin);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      相关资源
      最近更新 更多