【问题标题】:Find the literal resource key with the ResourceManager and nameof operator使用 ResourceManager 和 nameof 运算符查找文字资源键
【发布时间】:2016-04-14 18:22:27
【问题描述】:

我必须访问弱类型的资源文件,这意味着我必须通过 ResourceManager 传递完整的命名空间 + 文件名来加载/访问资源。

 var rm = new ResourceManager("namespace.name.locale.brand", Assembly.GetExecutingAssembly());

我通过“myImage”以非重构安全方法访问我的资源图像。

string imageUrl = rm.GetString("myImage");

想象一下,我有许多具有不同语言环境/品牌名称的 .resx 文件。它们都有不同的图像,但它们具有相同的键。因此我无法访问那些静态类型的资源,因为我只知道运行时正确的资源。

但我希望有一种将 nameof 运算符和资源管理器实例结合起来的棘手方法。

有谁知道这个棘手的方法?

请不要建议以静态类型的方式访问任何这些 .resx 文件,并将带有 nameof 的密钥传递给上述 .GetString() 方法。

如果没有使用 nameof 运算符的解决方案,那么欢迎使用任何工具 ;-)

【问题讨论】:

    标签: c# embedded-resource c#-6.0 nameof


    【解决方案1】:

    由于您不想拥有静态类型的资源,因此除了手动更新代码之外别无他法。

    但是,您仍然可以创建包装器来访问资源。通过创建包装器,您可以将访问集中在一个文件中,您还可以使用重命名 F2 一次性更改它。

    public class ResourceWrapper
    {
        private ResourceManager rm;
    
        public ResourceWrapper(string name) :
            this(name, Assembly.GetCallingAssembly())
        {
        }
        public ResourceWrapper(string name, Assembly assembly)
        {
            rm = new ResourceManager(name, assembly);
        }
    
        public string myImage => rm.GetString(nameof(myImage));
    }
    

    或者,您可以静态链接到其中一个资源文件并将其用作nameof名称提供者。喜欢:

    string imageUrl = rm.GetString(nameof(DummyResource.myImage));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多