11

想象一下,您正在处理一个由数百个程序集组成的 .Net 4.0 项目,每个程序集都有自己的用于本地化的资源文件 (.resx)。通过 ResXFileCodeGenerator 自动生成的类(创建“ResourceFile.Designer.cs”文件)从 C# 访问本地化字符串:string test = ResourceFile.TestString;

每个程序集都有其特有的本地化字符串,但也有所有程序集共有的字符串。您告诉自己,在“父”资源文件中包含这些“公共字符串”会很好,如果“本地”资源文件中的资源键不可用,代码将退回到该文件中。然后你说“嘿!继承可以在这里工作。” 事实上,在自动生成的设计器文件中执行类似的操作确实有效: internal class ResourceFile : ParentResourceFile 也就是说,未定义在ResourceFile中但定义在 中的字符串ParentResourceFile仍然可以使用ResourceFile.StringInParentFile.

但是设计器文件的标题中的某些内容让您感到困扰:“对此文件的更改可能会导致不正确的行为,并且如果重新生成代码将会丢失 ”另外,您知道在自动生成的设计器文件中播放是不受欢迎的。所以你来到这里,你问:

  • ResXFileCodeGenerator 何时生成/重新生成设计器类?
  • 有没有办法关闭自动生成?
  • 我们是否必须放弃 ResXFileCodeGenerator 的优势并实现我们自己的 ResourceManager 处理?

然后你说“谢谢”。

4

1 回答 1

7

After investigating the issue for a while, I've settled for a workaround: do inheritance not on the resource files themselves, but on the classes that need to access the "parent" resources.

You only need to have a base class whose project includes a "master" resource file, and set that resource file's CustomTool property to PublicResXFileCodeGenerator (the "Public" part is important as it will create a public class, as opposed to an internal one). One restriction is that PublicResXFileCodeGenerator is only available starting with VS2008 (this CodeProject article could otherwise be helpful).

Then, in classes which need to access the "master" resources, simply inherit from the base class and access the resources like this:

public class ChildClass : BaseClass
{
    string test = BaseClass.BaseResourceFile.TestString; // a common resource
    string localResource = ResourceFile.OtherString;     // a local resource
}

One disadvantage with this solution is that you have to explicitly reference the BaseResourceFile to access resources defined there; there's no fallback to the parent class like there would be if inheritance was done directly between the Resource classes.

And for posterity, I'll answer my own questions:

  • When does ResXFileCodeGenerator generate/regenerate the designer class?

    Whenever a resource is added/removed/modified.

  • Is there a way to turn off that auto-generation?

    No. And anyway, a "code generator" tool without auto-generation would be pretty useless, don't you think?

  • Will we have to forego the advantages of ResXFileCodeGenerator and implement our own handling of ResourceManager?

    No, see above answer.

We also considered implementing a solution using "linked" files (from the "Add existing item" dialog, using the "Add as link" option) where one parent resource file would be linked to all our assemblies, but since our assemblies already inherit from a base class, it seemed much better to go the inheritance way.

I don't really feel comfortable accepting my own answer, so if anyone comes up with a better solution or improvements on my solution, I'd gladly accept that. That is, if anyone cares at all.

于 2011-08-26T14:51:26.950 回答