【问题标题】:Strongly type resource files in C#C#中的强类型资源文件
【发布时间】:2012-04-18 11:11:09
【问题描述】:

我有一个访问类库项目中文件的 Windows 应用程序。

public static class Global
{
    private static ResourceManager ResourceManager { get; set; }

    static Global ()
    {
        ResourceManager = new ResourceManager("MyClassLibraryProject.Resource", Assembly.GetExecutingAssembly());
    }

    private static string GetValue (string name)
    {
        return (ResourceManager.GetString(name, Options.CultureInfo));
    }

    public static string ProductName
    {
        get
        {
            return (GetValue(MethodBase.GetCurrentMethod().Name.Replace("get_", "")));
        }
    }
}
`

在此示例中,我手动创建了 ProductName 属性。有没有更简单的方法来访问资源文件中每一行的强类型名称?

【问题讨论】:

    标签: c# embedded-resource strong-typing


    【解决方案1】:

    这可能会满足您的需求:https://docs.microsoft.com/en-us/dotnet/framework/tools/resgen-exe-resource-file-generator

    由于资源属性类型是在运行时确定的,因此您需要一个工具来分析资源文件的预编译时间并生成所需的属性。 Resgen.exe 会执行此操作,但您也可以创建自定义 t4 脚本或其他内容。

    来自文档:

    以下命令读取基于 XML 的输入文件 myResources.resx 并写入名为 myResources.resources 的二进制资源文件。它还生成一个名为 MyFile.cs 的 C# 文件,其中包含一个名为 MyClass 的类,其中包含与输入文件中引用的资源匹配的强类型属性。 MyClass 类包含在名为 Namespace1 的命名空间中。

    resgen myResources.resx myResources.resources /str:C#,Namespace1,MyClass,MyFile.cs

    【讨论】:

    • 这是我发现的。 Visual Studio 2010 已经在构建时使用工具ResXFileCodeGenerator 生成了一个类文件。然而,该类的可访问性是internal,如果我更改它,它会在构建时被替换。有没有办法自定义这种行为,以便我可以指定公共访问修饰符?
    • 找到它here。不敢相信我错过了。
    猜你喜欢
    • 2010-09-19
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 2010-09-13
    • 2019-02-20
    相关资源
    最近更新 更多