You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何本地化System.CommandLine的.NET7 C#控制台应用默认帮助文本

解决System.CommandLine 2.0.0-beta4.22272.1默认帮助文本本地化问题

针对自定义选项本地化成功,但默认Help/Version选项及帮助标题(Description、Usage、Options等)始终显示英文的问题,结合该预览版的特性,可按以下步骤处理:

1. 确保本地化资源包正确部署

该预览版的System.CommandLine本地化资源不会自动随主包安装,需要手动添加对应文化的资源包引用:

<ItemGroup>
  <PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
  <!-- 添加需要的语言资源包 -->
  <PackageReference Include="System.CommandLine.resources.de" Version="2.0.0-beta4.22272.1" PrivateAssets="all" />
  <PackageReference Include="System.CommandLine.resources.fr" Version="2.0.0-beta4.22272.1" PrivateAssets="all" />
</ItemGroup>

构建项目后,检查输出目录是否存在对应文化的子文件夹(如de、fr),且文件夹内包含System.CommandLine.resources.dll,这是资源加载的前提。

2. 提前设置UI文化(关键步骤)

由于预览版中LocalizationResources为内部类,无法直接替换,但资源加载是懒加载机制,必须在创建任何System.CommandLine对象前设置UI文化,才能触发对应语言资源的加载:

using System.Globalization;
using System.Threading;
using System.CommandLine;

// 必须在RootCommand/Command初始化前执行
var targetCulture = new CultureInfo("de-DE");
CultureInfo.DefaultThreadCurrentUICulture = targetCulture;
Thread.CurrentThread.CurrentUICulture = targetCulture;

// 后续初始化命令行逻辑
var rootCommand = new RootCommand("你的命令描述");
// 添加自定义选项、命令...
await rootCommand.InvokeAsync(args);

注意:若在命令行对象创建后再修改文化,已加载的英文资源不会自动切换。

3. 自定义环境变量控制(替代DOTNET_CLI_UI_LANGUAGE)

DOTNET_CLI_UI_LANGUAGE仅针对.NET CLI自身,对自定义应用无效。可通过自定义环境变量实现动态切换:

var uiLang = Environment.GetEnvironmentVariable("APP_UI_LANG") ?? "en-US";
var targetCulture = new CultureInfo(uiLang);
CultureInfo.DefaultThreadCurrentUICulture = targetCulture;
Thread.CurrentThread.CurrentUICulture = targetCulture;

启动应用前设置环境变量(如set APP_UI_LANG=fr-FR)即可切换到对应语言。

4. 预览版临时替代:自定义帮助生成器

若资源包方式仍无法生效,可直接覆盖帮助文本的生成逻辑,完全自定义所有默认文本:

using System.CommandLine.Help;

var rootCommand = new RootCommand("本地化测试命令");
rootCommand.SetHelpBuilder(builder =>
{
    builder.CustomizeLayout(_ =>
    {
        return HelpBuilder.DefaultLayout(_).Select(section =>
        {
            // 替换各帮助板块的标题文本
            return section.Key switch
            {
                HelpSectionKeys.Description => (section.Key, "Beschreibung:"),
                HelpSectionKeys.Usage => (section.Key, "Verwendung:"),
                HelpSectionKeys.Options => (section.Key, "Optionen:"),
                _ => section
            };
        });
    });
});

这种方式不受资源包限制,可灵活定制所有帮助内容。

内容的提问来源于stack exchange,提问作者KargWare

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 01:11:28