.resx 文件的每个变体都应该生成自己的 Designer.cs 文件吗?

问题描述 投票:0回答:1

我在官方文档中找不到太多关于

.Designer.cs
文件与
.resx
文件如何工作的信息,并且谷歌搜索这种情况也没有找到任何有用的信息。


我目前正在做的项目需要支持多种语言。因此,它有本地化文件:

  • 本地化.resx
  • Localization.en.resx
  • 验证.resx
  • Validation.en.resx

注意:英语不是默认语言。

我注意到,除了

.resx
文件之外,我们还有一些
Designer.cs
文件。具体来说,我们有以下几个:

  • 本地化.Designer.cs
  • Localization.en.Designer.cs
  • 验证.Designer.cs

由于某种原因,

Validation.en.resx
没有相应的
.en.Designer.cs
文件。

如果我们对

.en.resx
文件进行修改,则不会为其生成设计器文件。不过,这些改变仍然有效。访问我们的网站并将文化设置为英语会显示英语价值观。查看我们的 Git 状态,其他地方似乎没有
.en.Designer.cs
文件,并且我们的
.gitignore
文件没有忽略它。

要生成

Validation.en.Designer.cs
文件,我尝试过:

  • 禁用代码生成并将其重新启用为公共
  • 通过“运行自定义工具”操作使用 VS2022
  • 使用 Rider 进行“生成资源”操作
  • 创建空白
    .resx
    /
    .en.resx
    文件并手动移动其中的值
  • 手动更新
    .csproj
    文件以确保其具有与其他文件相同的 ResX 代码

唯一有效的方法是创建一个空的

Validator.en.Designer.cs
文件,该文件会立即填充正确的值。

但是,当团队成员对

.en.resx
文件进行更改时,
.en.Designer
文件不会更新,即使他们的更改在编译/运行应用程序时起作用。不过,对默认
.resx
文件 do 的更改会导致对
.Designer.cs
文件的更改。

那么我们应该有一个

.en.Designer.cs
文件和我们的
.en.resx
文件吗?或者默认的
.Designer.cs
文件应该处理基于本地选择正确的
.resx
源,而我们的项目中只有额外的文件?

c# code-generation rider resx
1个回答
2
投票

简短的回答是,不,每个本地化资源文件都没有设计器文件。

C# 文件实际上并不包含 resx 文件的

Value
部分。相反,它生成代码来查找资源文件中的值,这还包括用于文化相关查找的代码。您可以在主 resx 文件生成的设计器文件中看到这一点,其中有一段 C# 代码显示(为了简洁而重新格式化):

public static global::System.Globalization.CultureInfo Culture {
    get { return resourceCulture; }
    set { resourceCulture = value; }
}

这意味着有内置的本地化支持,因此当您设置文化时:

Resources.Validation.Culture = new CultureInfo("en");

...然后稍后引用本地化字符串(以

Greeting
为例):

Console.WriteLine(Resources.Validation.Greeting);

...它将自动选择正确的资源。如果没有找到字符串,它将默认为主 resx 文件。

示例

假设您有三个资源文件:

  • 主要一个:Validation.resx,包含(
    Anatid
    ,
    Duck-translation here
    )
  • 英语:Validation.en.resx,包含 (
    Anatid
    ,
    Duck
    )
  • 日语:Validation.ja-JP.resx,包含 (
    Anatid
    ,
    カモ
    )

使用它们:

foreach (string loc in new[] { "en", "ja-JP", "sr-Cyrl-RS" })
{
    Resources.Validation.Culture = new CultureInfo(loc);
    Console.WriteLine(Resources.Validation.Anatid);
}
/* Outputs:
Duck
カモ (Or ??. `chcp 932` if you really want to see katakana. Point is, it looks up the value.)
Duck-translation here
*/

对于其他功能,您可以按照此处列出的说明进行操作,但这可能超出您需要执行的操作。

© www.soinside.com 2019 - 2024. All rights reserved.