春冰 發表於 2025-11-7 07:29:00

dotnet 读 WPF 源代码 学习使用 Microsoft.DotNet.Arcade.Sdk 处理代码里的多语言

<p>在 dotnet 庞大的生态集里,打包工具链是开源中很重要的部分工作。通过 https://github.com/dotnet/arcade 将打包中重复的工作放在一个仓库中,减少基础设施能力在多个项目中重复进行。就像我所在的团队开源的 DotNETBuildSDK 项目一样,提供各种构建工具用在各个项目里面</p>
<p>翻遍整个 WPF 仓库,都无法直接找到任何的从 Strings.resx 和对应的 xlf 文件生成多语言卫星程序集的逻辑。这是因为多语言的核心转换是放在 Microsoft.DotNet.Arcade.Sdk 里面,在 WPF 仓库里面只有一些配置项</p>
<p>整个 WPF 开源仓库的组织是相对清晰的,所有和构建相关的配置都放在 eng 文件夹里面。其中对 Microsoft.DotNet.Arcade.Sdk 的引用分别放在 <code>eng\WpfArcadeSdk\Sdk\Sdk.props</code> 和 <code>eng\WpfArcadeSdk\Sdk\Sdk.targets</code> 文件里。核心代码只有以下这两句</p>
<pre><code class="language-xml">&lt;!-- Importing Arcade's Sdk.props should always be the first thing we do. However this is not a hard rule,
       it's just a convention for ensuring correctness and consistency in our build environment. If anything
       does need to be imported before, it should be documented why it is needed. --&gt;
&lt;Import Project="Sdk.props" Sdk="Microsoft.DotNet.Arcade.Sdk" /&gt;

&lt;Import Project="Sdk.targets" Sdk="Microsoft.DotNet.Arcade.Sdk" /&gt;
</code></pre>
<p>多语言配置部分的逻辑放在 <code>eng\WpfArcadeSdk\tools\SystemResources.props</code> 文件里,其代码较多,咱就先不展开细看</p>
<p>从 WPF 代码仓库里面是没有看到详尽的多语言转换过程逻辑的,但看了这几个文件也够咱自己学习模仿 WPF 用 Microsoft.DotNet.Arcade.Sdk 处理代码里的多语言的方式。接下来我将新建一个 WPF 空项目,在此和大家演示使用 Microsoft.DotNet.Arcade.Sdk 处理多语言,相信大家能够学会用此构建工具生成多语言程序集</p>
<p>新建一个空白的 WPF 项目</p>
<p>虽然按照 .NET 的惯例,使用一个库的第一件事就是用 NuGet 进行库的安装。但 Microsoft.DotNet.Arcade.Sdk 比较特殊,这是一个 SDK 而不是一个 Library 库。直接使用 NuGet 安装会报告以下错误</p>
<pre><code>包“Microsoft.DotNet.Arcade.Sdk 11.0.0-beta.25556.1”具有一个包类型“MSBuildSdk”,项目“Xxxxx”不支持该类型。
</code></pre>
<p>正确的使用方法如下</p>
<p>第一步是添加 NuGet.config 文件,设置使用 dotnet-eng 源。因为 Microsoft.DotNet.Arcade.Sdk 库是没有放在公网 NuGet 源里面的。修改之后的 NuGet.config 文件内容如下</p>
<pre><code class="language-xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;configuration&gt;
&lt;packageSources&gt;
    &lt;clear /&gt;
    &lt;!--End: Package sources managed by Dependency Flow automation. Do not edit the sources above.--&gt;
    &lt;add key="dotnet-eng" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json" /&gt;
   
&lt;/packageSources&gt;
&lt;/configuration&gt;
</code></pre>
<p>第二步是添加 global.json 文件,设置 Microsoft.DotNet.Arcade.Sdk 的版本。这一步就类似于使用 NuGet 进行安装的过程,只不过用的是 SDK 的方式</p>
<pre><code class="language-json">{
"msbuild-sdks":
{
    "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25411.109"
}
}
</code></pre>
<p>第三步就是在 csproj 项目文件里面添加引用,代码如下</p>
<pre><code class="language-xml">&lt;Import Project="Sdk.props" Sdk="Microsoft.DotNet.Arcade.Sdk" /&gt;
&lt;Import Project="Sdk.targets" Sdk="Microsoft.DotNet.Arcade.Sdk" /&gt;
</code></pre>
<p>如此三步就可以完成 Microsoft.DotNet.Arcade.Sdk 库安装</p>
<p>完成安装之后,就可以尝试多语言的加入了。只需放入 resx 文件,无论命名和放在哪个文件夹内。为了简单起见,我随便从 WPF 仓库拷贝了一个 Strings.resx 文件,编辑之后的内容如下</p>

<p><img src="https://img2024.cnblogs.com/blog/1080237/202511/1080237-20251107072855230-443161993.png" alt="" loading="lazy"></p>
<p>此时直接构建肯定是没有效果的,因为还没有设置 GenerateResxSource 属性为 true 值,用于配置让 Arcade 进行多语言生成</p>
<pre><code class="language-xml">&lt;PropertyGroup&gt;
    &lt;GenerateResxSource&gt;true&lt;/GenerateResxSource&gt;
&lt;/PropertyGroup&gt;
</code></pre>
<p>再设置 EmbeddedResource 属性,配置好生成的类型的命名空间和类名,配置的代码如下</p>
<pre><code class="language-xml">&lt;ItemDefinitionGroup&gt;
    &lt;EmbeddedResource&gt;
      &lt;GenerateSource&gt;true&lt;/GenerateSource&gt;
      &lt;ManifestResourceName&gt;FxResources.$(AssemblyName).SR&lt;/ManifestResourceName&gt;
      &lt;ClassName&gt;MS.Utility.SR&lt;/ClassName&gt;
    &lt;/EmbeddedResource&gt;
&lt;/ItemDefinitionGroup&gt;
</code></pre>
<p>以上代码里面的 <code>GenerateSource</code> 设置为 true 表示当前项用来配置多语言的生成。以上代码的 <code>ManifestResourceName</code> 只是一个用来标识资源存在的程序集,用来执行 <code>typeof</code> 获取 ResourceManager 的资源,命名上比较随意。以上的 <code>ClassName</code> 为重点部分,用来表示从 resx 文件应该生成的类型全名,采用命名空间加类型名的表示法。如 <code>MS.Utility.SR</code> 将生成命名空间为 <code>MS.Utility</code> 且类型名为 <code>SR</code> 的类型</p>
<p>通过 <code>ClassName</code> 的配置,即可让各个程序集采用不同的命名空间配置。如在 WPF 仓库的 <code>eng\WpfArcadeSdk\tools\SystemResources.props</code> 文件里,就使用了以下类似的代码为各个程序集配置不同的命名空间</p>
<pre><code class="language-xml">&lt;ItemDefinitionGroup&gt;
    &lt;EmbeddedResource&gt;
      &lt;GenerateSource&gt;true&lt;/GenerateSource&gt;
      &lt;ManifestResourceName&gt;FxResources.$(AssemblyName).SR&lt;/ManifestResourceName&gt;

      &lt;ClassName Condition="'$(AssemblyName)'=='PresentationBuildTasks'"&gt;MS.Utility.SR&lt;/ClassName&gt;
      &lt;ClassName Condition="'$(AssemblyName)'=='UIAutomationTypes'"&gt;System.SR&lt;/ClassName&gt;
      &lt;ClassName Condition="'$(AssemblyName)'=='WindowsBase'"&gt;MS.Internal.WindowsBase.SR&lt;/ClassName&gt;
      ...
      &lt;ClassName Condition="'$(AssemblyName)'=='PresentationCore'"&gt;MS.Internal.PresentationCore.SR&lt;/ClassName&gt;
      &lt;ClassName Condition="'$(AssemblyName)'=='System.Xaml'"&gt;System.SR&lt;/ClassName&gt;
      &lt;Classname Condition="'%(ClassName)'==''"&gt;System.SR&lt;/Classname&gt;
    &lt;/EmbeddedResource&gt;
&lt;/ItemDefinitionGroup&gt;
</code></pre>
<p>以上逻辑就能够完成多语言生成的配置</p>
<p>然而现在还不能通过构建,一构建将提示类似如下的错误</p>
<pre><code>C:\Users\lindexi\.nuget\packages\microsoft.dotnet.arcade.sdk\10.0.0-beta.25411.109\tools\Version.BeforeCommonTargets.targets(88,5): error MSB4184: 无法计算表达式“"".GetValue(1)”。Index was outside the bounds of the array.
</code></pre>
<p>这是因为在 Version.BeforeCommonTargets.targets 文件里面存在如下代码</p>
<pre><code class="language-xml">&lt;PropertyGroup&gt;
    &lt;VersionPrefix Condition="'$(MajorVersion)' != '' and '$(MinorVersion)' != ''"&gt;$(MajorVersion).$(MinorVersion).$(::ValueOrDefault('$(PatchVersion)', '0'))&lt;/VersionPrefix&gt;
&lt;/PropertyGroup&gt;

&lt;PropertyGroup Condition="'$(PreReleaseVersionLabel)' == ''"&gt;
    &lt;_VersionPrefixMajor&gt;$(VersionPrefix.Split('.'))&lt;/_VersionPrefixMajor&gt;
    &lt;_VersionPrefixMinor&gt;$(VersionPrefix.Split('.'))&lt;/_VersionPrefixMinor&gt;
    &lt;VersionPrefix&gt;$(_VersionPrefixMajor).$(_VersionPrefixMinor).$(::ValueOrDefault($(_PatchNumber), '0'))&lt;/VersionPrefix&gt;
    &lt;VersionSuffix/&gt;
&lt;/PropertyGroup&gt;
</code></pre>
<p>尽管我认为这是 Microsoft.DotNet.Arcade.Sdk 库的设计不够开箱即用,但考虑到这是一个专用的库,这一点也能接受。继续编辑 csproj 项目文件,添加如下代码,添加版本号信息</p>
<pre><code class="language-xml">&lt;PropertyGroup&gt;
    &lt;MajorVersion&gt;1&lt;/MajorVersion&gt;
    &lt;MinorVersion&gt;2&lt;/MinorVersion&gt;
&lt;/PropertyGroup&gt;
</code></pre>
<p>如此即可完成构建准备,尝试构建一下。此时细心的伙伴也许就发现了,在 obj 文件夹下,生成了 <code>obj\Debug\net9.0-windows\MS.Utility.SR.cs</code> 文件,且在此文件里面填满了在 Strings.resx 资源字典定义的多语言项。其生成代码大概如下</p>
<pre><code class="language-csharp">using System.Reflection;

namespace FxResources.QewheefanallJabayhejage
{
    internal static class SR { }
}
namespace MS.Utility
{
    internal static partial class SR
    {
      private static global::System.Resources.ResourceManager s_resourceManager;
      internal static global::System.Resources.ResourceManager ResourceManager =&gt; s_resourceManager ?? (s_resourceManager = new global::System.Resources.ResourceManager(typeof(FxResources.QewheefanallJabayhejage.SR)));
      internal static global::System.Globalization.CultureInfo Culture { get; set; }
#if !NET20
      
#endif
      internal static string GetResourceString(string resourceKey, string defaultValue = null) =&gt;ResourceManager.GetString(resourceKey, Culture);
      /// &lt;summary&gt;Enumerating attached properties on object '{0}' threw an exception.&lt;/summary&gt;
      internal static string @APSException =&gt; GetResourceString("APSException");
      /// &lt;summary&gt;Add value to collection of type '{0}' threw an exception.&lt;/summary&gt;
      internal static string @AddCollection =&gt; GetResourceString("AddCollection");
      /// &lt;summary&gt;Add value to dictionary of type '{0}' threw an exception.&lt;/summary&gt;
      internal static string @AddDictionary =&gt; GetResourceString("AddDictionary");
    }
}
</code></pre>
<p>细心的伙伴还能看到,此时在项目里面被新建了 xlf 文件夹,在此文件夹内充满了各个语言文化对应的 xlf 文件。这些 xlf 文件是为翻译人员准备的,方便对接翻译平台进行翻译。每个 xlf 文件都会在 obj 文件夹生成对应的 resx 文件,再由 resx 文件生成对应的程序集</p>

<p><img src="https://img2024.cnblogs.com/blog/1080237/202511/1080237-20251107072855902-1048057976.png" alt="" loading="lazy"></p>
<p>这里的 xlf 文件是采用 https://en.wikipedia.org/wiki/XLIFF 多语言翻译规范的文件,这是一个现有的规范的格式。其内容大概如下</p>
<pre><code class="language-xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"&gt;
&lt;file datatype="xml" source-language="en" target-language="zh-Hans" original="../Strings.resx"&gt;
    &lt;body&gt;
      &lt;trans-unit id="APSException"&gt;
      &lt;source&gt;Enumerating attached properties on object '{0}' threw an exception.&lt;/source&gt;
      &lt;target state="translated"&gt;枚举对象“{0}”的附加属性时引发了异常。&lt;/target&gt;
      &lt;note /&gt;
      &lt;/trans-unit&gt;
      &lt;trans-unit id="AddCollection"&gt;
      &lt;source&gt;Add value to collection of type '{0}' threw an exception.&lt;/source&gt;
      &lt;target state="translated"&gt;向类型为“{0}”的集合中添加值引发了异常。&lt;/target&gt;
      &lt;note /&gt;
      &lt;/trans-unit&gt;
      &lt;trans-unit id="AddDictionary"&gt;
      &lt;source&gt;Add value to dictionary of type '{0}' threw an exception.&lt;/source&gt;
      &lt;target state="new"&gt;Add value to dictionary of type '{0}' threw an exception.&lt;/target&gt;
      &lt;note /&gt;
      &lt;/trans-unit&gt;
    &lt;/body&gt;
&lt;/file&gt;
&lt;/xliff&gt;
</code></pre>
<p>可以看到 XLIFF 格式里面可以为翻译人员提供双语对照,也能通过 <code>state="translated"</code> 还是 <code>state="new"</code> 标记出已经翻译的还是新添加的多语言项</p>
<p>从这里也能看到 Microsoft.DotNet.Arcade.Sdk 的好用之处,只需添加 resx 文件,就会自动生成各个语言文化对应的 xlf 文件,方便翻译人员对接</p>
<p>以下是我的最简使用 Microsoft.DotNet.Arcade.Sdk 对接多语言的 csproj 项目的代码</p>
<pre><code class="language-xml">&lt;Project Sdk="Microsoft.NET.Sdk"&gt;

&lt;PropertyGroup&gt;
    &lt;OutputType&gt;WinExe&lt;/OutputType&gt;
    &lt;TargetFramework&gt;net9.0-windows&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;UseWPF&gt;true&lt;/UseWPF&gt;
&lt;/PropertyGroup&gt;

&lt;PropertyGroup&gt;
    &lt;MajorVersion&gt;1&lt;/MajorVersion&gt;
    &lt;MinorVersion&gt;2&lt;/MinorVersion&gt;
&lt;/PropertyGroup&gt;

&lt;PropertyGroup&gt;
    &lt;GenerateResxSource&gt;true&lt;/GenerateResxSource&gt;

    &lt;!-- &lt;GenerateResxSourceOmitGetResourceString&gt;true&lt;/GenerateResxSourceOmitGetResourceString&gt; --&gt;
&lt;/PropertyGroup&gt;

&lt;Import Project="Sdk.props" Sdk="Microsoft.DotNet.Arcade.Sdk" /&gt;
&lt;Import Project="Sdk.targets" Sdk="Microsoft.DotNet.Arcade.Sdk" /&gt;

&lt;ItemDefinitionGroup&gt;
    &lt;EmbeddedResource&gt;
      &lt;GenerateSource&gt;true&lt;/GenerateSource&gt;
      &lt;ManifestResourceName&gt;FxResources.$(AssemblyName).SR&lt;/ManifestResourceName&gt;
      &lt;ClassName&gt;MS.Utility.SR&lt;/ClassName&gt;
      &lt;/EmbeddedResource&gt;
&lt;/ItemDefinitionGroup&gt;
&lt;/Project&gt;
</code></pre>
<p>以上被注释掉的 <code>GenerateResxSourceOmitGetResourceString</code> 属性用来配置 Microsoft.DotNet.Arcade.Sdk 生成的类型里面,不要生成 GetResourceString 等代码。如此即可在自己程序集里面自己定义多语言获取的类型,提供更高的自由。在 WPF 仓库里面,就是自己定义的 GetResourceString 方法,用来处理多语言找不到的情况</p>
<p>也许有伙伴好奇在 Microsoft.DotNet.Arcade.Sdk 底层是如何对接多语言代码的生成的。事实上这部分逻辑也十分简单,从 https://github.com/dotnet/arcade 仓库可以找到明确的代码</p>
<p>先是在 GenerateResxSource.targets 文件里面执行对接逻辑,核心代码如下</p>
<pre><code class="language-xml">&lt;Target Name="_GenerateResxSource"
          BeforeTargets="BeforeCompile;CoreCompile"
          DependsOnTargets="PrepareResourceNames;
                            _GetEmbeddedResourcesWithSourceGeneration;
                            _BatchGenerateResxSource"&gt;
    &lt;ItemGroup&gt;
      &lt;GeneratedResxSource Include="@(EmbeddedResourceSGResx-&gt;'%(SourceOutputPath)')" /&gt;
      &lt;FileWrites Include="@(GeneratedResxSource)" /&gt;
      &lt;Compile Include="@(GeneratedResxSource)" /&gt;
    &lt;/ItemGroup&gt;
&lt;/Target&gt;

&lt;Target Name="_BatchGenerateResxSource"
          Inputs="@(EmbeddedResourceSGResx)"
          Outputs="%(EmbeddedResourceSGResx.SourceOutputPath)"&gt;

    &lt;Microsoft.DotNet.Arcade.Sdk.GenerateResxSource
      Language="$(Language)"
      ResourceFile="%(EmbeddedResourceSGResx.FullPath)"
      ResourceName="%(EmbeddedResourceSGResx.ManifestResourceName)"
      ResourceClassName="%(EmbeddedResourceSGResx.ClassName)"
      AsConstants="%(EmbeddedResourceSGResx.GenerateResourcesCodeAsConstants)"
      OmitGetResourceString="$(GenerateResxSourceOmitGetResourceString)"
      IncludeDefaultValues="$(GenerateResxSourceIncludeDefaultValues)"
      EmitFormatMethods="$(GenerateResxSourceEmitFormatMethods)"
      OutputPath="%(EmbeddedResourceSGResx.SourceOutputPath)" /&gt;
&lt;/Target&gt;
</code></pre>
<p>可见就是从 <code>_BatchGenerateResxSource</code> 调用 <code>Microsoft.DotNet.Arcade.Sdk.GenerateResxSource</code> 执行生成逻辑。在 <code>_GenerateResxSource</code> 里面将生成的文件加入构建</p>
<p>上面代码的 <code>EmbeddedResourceSGResx</code> 内容仅是取出本文在 csproj 的 ItemDefinitionGroup 里面定义的属性内容,再配合添加一些过滤条件而已</p>
<p>核心的 GenerateResxSource 生成类的定义代码如下</p>
<pre><code class="language-csharp">    public sealed class GenerateResxSource : Microsoft.Build.Utilities.Task
    {
      private const int maxDocCommentLength = 256;

      /// &lt;summary&gt;
      /// Language of source file to generate.Supported languages: CSharp, VisualBasic
      /// &lt;/summary&gt;
      
      public string Language { get; set; }

      /// &lt;summary&gt;
      /// Resources (resx) file.
      /// &lt;/summary&gt;
      
      public string ResourceFile { get; set; }

      /// &lt;summary&gt;
      /// Name of the embedded resources to generate accessor class for.
      /// &lt;/summary&gt;
      
      public string ResourceName { get; set; }

      /// &lt;summary&gt;
      /// Optionally, a namespace.type name for the generated Resources accessor class.Defaults to ResourceName if unspecified.
      /// &lt;/summary&gt;
      public string ResourceClassName { get; set; }

      /// &lt;summary&gt;
      /// If set to true the GetResourceString method is not included in the generated class and must be specified in a separate source file.
      /// &lt;/summary&gt;
      public bool OmitGetResourceString { get; set; }

      /// &lt;summary&gt;
      /// If set to true, emits constant key strings instead of properties that retrieve values.
      /// &lt;/summary&gt;
      public bool AsConstants { get; set; }

      /// &lt;summary&gt;
      /// If set to true calls to GetResourceString receive a default resource string value.
      /// &lt;/summary&gt;
      public bool IncludeDefaultValues { get; set; }

      /// &lt;summary&gt;
      /// If set to true, the generated code will include .FormatXYZ(...) methods.
      /// &lt;/summary&gt;
      public bool EmitFormatMethods { get; set; }

      
      public string OutputPath { get; set; }

      private enum Lang
      {
            CSharp,
            VisualBasic,
      }

      ...
    }
</code></pre>
<p>其生成逻辑是根据 C# 或 VB 进行拼接字符串方式生成的多语言代码的</p>
<p>读取 resw 字典也是直接使用 XDocument 的方式读取,核心代码如下</p>
<pre><code class="language-csharp">            string classIndent = (namespaceName == null ? "" : "    ");
            string memberIndent = classIndent + "    ";

            var strings = new StringBuilder();

            foreach (var node in XDocument.Load(ResourceFile).Descendants("data"))
            {
                string name = node.Attribute("name")?.Value;
                string value = node.Elements("value").FirstOrDefault()?.Value.Trim();

                strings.AppendLine($"{memberIndent}internal static string @{identifier} =&gt; GetResourceString(\"{name}\"{defaultValue});");
            }
</code></pre>
<p>实际的代码比我以上有删减部分略微复杂,如果大家感兴趣,还请自行去查看源代码</p>
<p>本文代码放在 github 和 gitee 上,可以使用如下命令行拉取代码。我整个代码仓库比较庞大,使用以下命令行可以进行部分拉取,拉取速度比较快</p>
<p>先创建一个空文件夹,接着使用命令行 cd 命令进入此空文件夹,在命令行里面输入以下代码,即可获取到本文的代码</p>
<pre><code>git init
git remote add origin https://gitee.com/lindexi/lindexi_gd.git
git pull origin 69bd783e97b03e767017ebbbe61aad89b9a8104d
</code></pre>
<p>以上使用的是国内的 gitee 的源,如果 gitee 不能访问,请替换为 github 的源。请在命令行继续输入以下代码,将 gitee 源换成 github 源进行拉取代码。如果依然拉取不到代码,可以发邮件向我要代码</p>
<pre><code>git remote remove origin
git remote add origin https://github.com/lindexi/lindexi_gd.git
git pull origin 69bd783e97b03e767017ebbbe61aad89b9a8104d
</code></pre>
<p>获取代码之后,进入 WPFDemo/QewheefanallJabayhejage 文件夹,即可获取到源代码</p>
<p>更多技术博客,请参阅 博客导航</p>


</div>
<div id="MySignature" role="contentinfo">
    <p>博客园博客只做备份,博客发布就不再更新,如果想看最新博客,请访问 https://blog.lindexi.com/</p>

<p>如图片看不见,请在浏览器开启不安全http内容兼容</p>

<img alt="知识共享许可协议" style="border-width: 0" src="https://licensebuttons.net/l/by-nc-sa/4.0/88x31.png"><br>本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名[林德熙](https://www.cnblogs.com/lindexi)(包含链接:https://www.cnblogs.com/lindexi ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我[联系](mailto:lindexi_gd@163.com)。<br><br>
来源:https://www.cnblogs.com/lindexi/p/19198245
頁: [1]
查看完整版本: dotnet 读 WPF 源代码 学习使用 Microsoft.DotNet.Arcade.Sdk 处理代码里的多语言