How can we get the T4 template to generate code based on a .cs file that the user is editing?

自闭症网瘾萝莉.ら 提交于 2019-12-13 03:38:29

问题


I'm trying to create a T4 template that will save our developers from creating a lot of boilerplate code that's necessary in our framework. Let's say the developer creates an interface and marks it with our custom attribute. I would like it so that any interface marked with that custom attribute is enhanced by additional methods, which means my T4 template would have to generate partial classes on the fly. However, I would like it so that this automatic generation happens on the fly and seamlessly, preferably when the internal automatic compilation that's used for intellisense happens. You know how when you create a new class in Visual Studio and you switch to another source file and start using that class you didn't have to save or compile it, Intellisense was able to see the new class you created right away? I'd like the same automatic behavior with the code generated from my T4 template. Any thoughts?


回答1:


You cannot do what you want to do easily, but here are some options ordered from easiest to most likely what you want (hardest).

  1. Create code snippets

  2. Create a Visual Studio Item Template

  3. Use Castle DynamicProxy to create the extra bits at run time.

  4. Create a separate project to hold the T4 generated classes as described in my answer here

  5. As a pre-step to your project build (modify .csproj file to do this), you can compile the source code from which you want to generated code and then reflect on that, generate the code and then add it to the project before the real compile step. This is what the MSR Orleans project does. You can read their source code here. This is really cool! :-)



来源:https://stackoverflow.com/questions/32037210/how-can-we-get-the-t4-template-to-generate-code-based-on-a-cs-file-that-the-use

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