如何从.NET资源(RESX)文件中获取字符串值

Lea*_*ner 15 .net c# resx

这是我的RESX文件的样子:

Name            Value        Comments
Rule_seconds    seconds      seconds
Rule_Sound      Sound        Sound
Run Code Online (Sandbox Code Playgroud)

我想要的是:按字符串名称值,如下所示:

public string GetResxNameByValue(string value)
{
// some code to get name value
}
Run Code Online (Sandbox Code Playgroud)

并按如下方式实现:

string str = GetResxNameByValue("seconds");
Run Code Online (Sandbox Code Playgroud)

所以这str将回来Rule_seconds

谢谢!

jur*_*ure 24

这可行

private string GetResxNameByValue(string value)
    {
            System.Resources.ResourceManager rm = new System.Resources.ResourceManager("YourNamespace.YourResxFileName", this.GetType().Assembly);


        var entry=
            rm.GetResourceSet(System.Threading.Thread.CurrentThread.CurrentCulture, true, true)
              .OfType<DictionaryEntry>()
              .FirstOrDefault(e => e.Value.ToString() ==value);

        var key = entry.Key.ToString();
        return key;

    }
Run Code Online (Sandbox Code Playgroud)

有一些额外的错误检查..


小智 5

您可以通过密钥直接访问:

    public  string gtresource(string rulename)
    {
        string value = null;
        System.Resources.ResourceManager RM = new System.Resources.ResourceManager("CodedUITestProject1.Resource1", this.GetType().Assembly);
        value = RM.GetString(rulename).ToString();

        if(value !=null && value !="")
        {
            return value;

        }
        else
        {
            return "";
        }

    }
Run Code Online (Sandbox Code Playgroud)

  • 在7行代码中,我看到了一些需要解决的问题:首先`RM.GetString(rulename)`已经返回一个字符串.没有必要调用`ToString()`.其次,`RM.GetString(rulename)`可以返回null是未找到的资源,这将引发一个`NullReferenceException`.第三,由于`NullReferenceException`,将永远不会使用null值到达`if(value!= null && value!="")`.最后,你可以用`return RM.GetString(rulename)替换所有if?的String.Empty;`. (3认同)
  • 这并没有解决原始问题,即您作为解决方案发布的内容的"反向".根据特定值,需要检索密钥... (3认同)