c# Generate c# code before compilation/buil (Like maven plugin in java)

隐身守侯 提交于 2019-12-12 13:13:51

问题


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?

Thanks.


回答1:


There are at least two options:

  1. Use T4
  2. Add a pre-build step to the build file.

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).


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

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.




回答2:


Try the Tangible T4 Editor. Its a plugin for Visual Studio that exposes the built in T4 Text Template functionality so you can use it to auto-generate C# files. It enables support for compile time generation of C# code within Visual Studio.

I used this to convert a .xml file into 2,600 lines of C# at compile time. Now, if I change the .xml file, and recompile, it will automatically regenerate the correct C# code.

It works like magic, and is completely seamless.




回答3:


Sounds like you want T4 Templates.



来源:https://stackoverflow.com/questions/7995028/c-sharp-generate-c-sharp-code-before-compilation-buil-like-maven-plugin-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!