c#在编译/构建之前生成c#代码(类似于Java中的maven插件) [英] c# Generate c# code before compilation/buil (Like maven plugin in java)

查看:272
本文介绍了c#在编译/构建之前生成c#代码(类似于Java中的maven插件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c#.net中有一个项目.
我需要挂钩"pre build"事件,这样我才能运行一个c#类,该类将为同一项目生成其他c#类.
我知道在Java中,您可以使用Maven插件生成源代码,是否可以在.net中使用?

I have a projet in c# .net.
I need to hook the "pre build" event so I can run a c# class that will generate other c# class to the same project.
I know that in java you can generate source code using maven plugin, is it possible in .net?

谢谢.

推荐答案

至少有两个选择:

  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.

这篇关于c#在编译/构建之前生成c#代码(类似于Java中的maven插件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆