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

dotnet cli自定义类模板创建时如何检测并自动设置命名空间

实现dotnet new自定义类模板命名空间自动检测方案

第一步:修改template.json配置

在原有配置基础上新增symbols节点,配置命名空间的解析规则:

{
    "$schema": "http://json.schemastore.org/template",
    "author": "name",
    "classifications": [ "core", "console", "class" ],
    "tags": {
      "language": "C#",
      "type": "item"
    },
    "identity": "Template.ClassTemplate",
    "name": "Editable Class Template",
    "shortName": "class",
    "sourceName": "Class1",
    // 新增以下命名空间配置
    "symbols": {
      "namespace": {
        "type": "parameter",
        "datatype": "string",
        "defaultValue": "DefaultNamespace",
        "replaces": "newClass",
        "description": "生成类的命名空间",
        "isRequired": false,
        "bindings": [
          {
            // 绑定当前项目的默认命名空间(RootNamespace属性)
            "binding": "msbuild:RootNamespace"
          },
          {
            // 自动拼接当前创建路径的子目录层级到命名空间
            "binding": "directory:namespace"
          }
        ]
      }
    }
}

第二步:模板文件无需额外修改

原有的Class1.cs模板内容不需要调整,配置中已经指定了replaces: "newClass",生成时会自动把模板中的newClass替换为解析到的命名空间值。

使用方式

自动检测命名空间

直接在目标项目的目录/子目录下执行创建命令即可,模板会自动读取项目的默认命名空间,再拼接当前子目录层级生成最终命名空间:
dotnet new class -n 类名
例如项目默认命名空间为MyApp,在项目下的Services/Utils子目录执行命令,生成的类命名空间自动为MyApp.Services.Utils。

手动指定命名空间

需要自定义命名空间时,新增--namespace参数传入自定义值即可:
dotnet new class -n 类名 --namespace 自定义命名空间

注意事项

  • 自动检测逻辑仅在.NET项目目录(存在.csproj/.vbproj等项目文件的目录)或其子目录下执行生效
  • 如果无法读取到项目命名空间,会使用配置中的defaultValue作为兜底命名空间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:45:04