首页 / C#开发 / 正文

C#/.NET应用程序编程开发中如何根据值获取资源文件(.resx)对应的键?

3249 1 发布于: 2019-11-22 读完约需5分钟

问题描述

在C#/.NET应用程序编程开发中,假如有这样的资源文件(.resx):

键        值
key_1    value_1
key_2    value_2

当前需要根据资源文件数据中的值获取对应的键名,比如知道资源文件数据值为value_1,通过C#/.NET程序如何获取到对应的键名key_1呢?

方案一

使用ResourceManager反射获取,如下:

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;

}

方案二

编写一个资源文件的帮助类,如下:

using System.Collections;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Threading;

public class ResourceHelper
{
    /// <summary>
    /// 资源帮助类
    /// </summary>
    /// <param name="resourceName"></param>
    /// <param name="assembly"></param>
    public ResourceHelper(string resourceName, Assembly assembly)
    {
        ResourceManager = new ResourceManager(resourceName, assembly);
    }

    private ResourceManager ResourceManager { get; set; }

    public string GetResourceName(string value)
    {
        DictionaryEntry entry = ResourceManager.GetResourceSet(Thread.CurrentThread.CurrentCulture, true, true).OfType<DictionaryEntry>().FirstOrDefault(dictionaryEntry => dictionaryEntry.Value.ToString() == value);
        return entry.Key.ToString();
    }

    public string GetResourceValue(string name)
    {
        string value = ResourceManager.GetString(name);
        return !string.IsNullOrEmpty(value) ? value : null;
    }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: .NET项目中实现多工程文件共用的方法

下一篇: .NET Framework 3.5,.NET Framework 4.5等.NET Framework版本官方下载地址汇总

本文永久链接码友网 » C#/.NET应用程序编程开发中如何根据值获取资源文件(.resx)对应的键?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册