我们如何让 T4 模板根据用户正在编辑的 .cs 文件生成代码? [英] How can we get the T4 template to generate code based on a .cs file that the user is editing?

查看:26
本文介绍了我们如何让 T4 模板根据用户正在编辑的 .cs 文件生成代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 T4 模板,该模板将使我们的开发人员免于创建框架中必需的大量样板代码.假设开发人员创建了一个接口并使用我们的自定义属性对其进行标记.我希望任何标有该自定义属性的接口都通过其他方法增强,这意味着我的 T4 模板必须即时生成部分类.但是,我希望这种自动生成能够即时无缝地发生,最好是在用于智能感知的内部自动编译发生时.您知道如何在 Visual Studio 中创建一个新类并切换到另一个源文件并开始使用该类时无需保存或编译它,Intellisense 能够立即看到您创建的新类吗?我想要与从我的 T4 模板生成的代码相同的自动行为.有什么想法吗?

解决方案

你不能轻易做你想做的事,但这里有一些选项,从最容易到最可能你想要的(最难)排序.

  1. 创建代码片段

  2. 创建Visual Studio 项目模板

  3. 使用 Castle DynamicProxy 在运行时创建额外的位.

  4. 创建一个单独的项目来保存 T4 生成的类,如 我的回答在这里

  5. 作为项目构建的前期步骤(修改 .csproj 文件以执行此操作),您可以编译要从中生成代码的源代码,然后对其进行反思,生成代码,然后添加在真正的编译步骤之前将它添加到项目中.这就是 MSR Orleans 项目所做的.您可以在此处阅读源代码.这真的很酷!:-)

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?

解决方案

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! :-)

这篇关于我们如何让 T4 模板根据用户正在编辑的 .cs 文件生成代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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