且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

c#在编译/构建之前生成c#代码(类似于Java中的maven插件)

更新时间:2023-10-01 13:28:10

至少有两个选择:

  1. 使用 T4
  2. 在构建文件中添加一个预构建步骤.

T4是用于生成代码的内置方法(并广泛用于ASP.NET MVC支架和实体框架类型生成).但是T4不直接支持编译时间生成.它要么在设计时(由开发人员触发(重新)生成),要么在运行时生成. (第三方工具可以增加生成编译时间).

T4 is the inbuilt way to do code generation (and widely used in ASP.NET MVC scaffolding and Entity Framework type generation). However T4 doesn't directly support compile time generation. It does either design time – with the developer triggering (re-)generation – or runtime generation; (third party tools can add compile time generation).

附录(6年后): Clarius.TransformOnBuild 之类的NuGet包可以也可以做到这一点.

Adendum (after 6 years): NuGet packages like Clarius.TransformOnBuild can also do this.

自定义MSBuild任务(包括运行外部程序)可用于创建代码,然后将其包含在编译中.在最简单的情况下,可以使用项目的预构建"设置(项目属性的构建事件"选项卡).直接在MSBuild中工作(.csproj是MSBuild文件)可提供更大的灵活性.

A custom MSBuild task (including running an external program) can be used to create code which is then included in the compile. In the simplest cases the "pre-build" setting of a project can be used (the Build Events tab of the project properties). Directly working in MSBuild (and a .csproj is a MSBuild file) gives more flexibility.