【问题标题】:How do I prevent nested C# classes with .resx files using the same named .resources file?如何使用相同命名的 .resources 文件防止嵌套的 C# 类与 .resx 文件?
【发布时间】:2023-01-15 14:25:01
【问题描述】:

为具有 .resx 文件的 C# 类生成 .resources 文件时,Visual Studio 2022 仅使用命名空间和外部类名称来生成 .resources 文件的名称。如果在同一外部类中嵌套了多个类(具有 .resx 文件),则 .resources 文件的名称将相同,从而导致错误 MSB3577。

无论如何要解决这个问题?比如.csproj文件里面的入口有没有设置输出名称的参数?还是在涉及 .resx 文件时避免使用嵌套类?

复制步骤:

  1. 在 Visual Studio 2022 中,使用 .NET Framework 4.6.2 创建一个名为“NestedResTest”的新 Windows 窗体控件库。

  2. 添加两个 Windows 窗体,Dialog1 和 Dialog2。文件 Dialog1.cs、Dialog1.Designer.cs 和 Dialog1.resx 以及 Dialog2 的相应文件将自动创建。 Dialog1 和 Dialog2 类都将位于命名空间 NestedResTest 中。

  3. 将 MSBuild 项目构建输出详细程度设置为“诊断”(工具 -> 选项 -> 项目和解决方案 -> 构建和运行)。

  4. 构建 NestedResTest。构建应该会成功。在生成输出中搜索带有“OutputResources=”的行,您应该会看到两个 .resources 文件: NestedResTest.Dialog1.resources NestedResTest.Dialog2.resources

  5. 编辑 Dialog1.cs 和 Dialog1.Designer.cs 并将 Dialog1 类放入分部类 InnerClass 中。

  6. 构建 NestedResTest。构建应该会成功。在生成输出中搜索带有“OutputResources=”的行,您应该会看到两个 .resources 文件: NestedResTest.InnerClass.resources NestedResTest.Dialog2.resources

  7. 编辑 Dialog2.cs 和 Dialog2.Designer.cs 并将 Dialog2 类放入分部类 InnerClass 中。

  8. 构建 NestedResTest。构建应该失败并出现错误 MSB3577。在生成输出中搜索带有“OutputResources=”的行,您应该会看到两个 .resources 文件,它们都具有相同的名称: NestedResTest.InnerClass.resources

【问题讨论】:

  • 您发现将 Form 类隐藏为嵌套类并不是一个好主意。为什么你必须这样做是非常不清楚的,解释一下有人可以提出更好的选择。

标签: c# winforms


【解决方案1】:

我假设您知道嵌套 Form 类的主要后果是失去设计师对设计表单的支持。也就是说,资源文件名的构建问题可以通过从

  1. 右键单击一个项目并卸载项目

  2. 对于嵌套Form类的资源文件,去掉<DependentUpon>标签,比如dialog1的资源应该是这样的,去掉<DependentUpon>Dialog1.cs</DependentUpon>后:

    <EmbeddedResource Include="Dialog1.resx">
    </EmbeddedResource>
    
  3. 右键单击项目并重新加载。

    构建并运行项目。您将看到资源已被应用并按预期工作。

【讨论】:

    猜你喜欢
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多