How do you use .net Reflection with T4?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 12:55:13

问题


I have a c# project which includes a Text Template. I would like this template to generate some SQL based on reflecting against the C# classes in the project.

How does one access the current project's contents using T4? Is it possible, and if so, is Reflection available, or is it access to just the raw source that must then be parsed?

Thanks in advance!


回答1:


How does one access the current project's contents using T4?

One way is to use the EnvDTE COM component. Googling T4 and EnvDTE should bring back plenty of examples.

Is it possible, and if so, is Reflection available, or is it access to just the raw source that must then be parsed?

Reflection is definitely available from T4. It works mostly as you would expect.

Oleg Sych has a number of great blog entries regarding common T4 usage scenarios, but there are plenty of other resources for T4 out there as well.




回答2:


Completely aside from locking problems, be careful using reflection within a T4 template. The template generator in VS2010 runs against version 4.0 of the Framework, so you could introduce unwanted dependencies if you're generating code for 3.5 or below.

I just found this out the hard way, after using reflection to decide whether to generate parameterless or parameterised calls to ToString for various BCL types. TimeSpan has only ToString() in 2.0, but 4.0 adds ToString(string) :P




回答3:


While this doesnt solve the locking problems (although ive heard that VS2010 does), you could try copy the dll to a temp location and just use that copied assembly..

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".txt" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.IO" #>
<#    
var newFileName = System.IO.Path.GetTempFileName();
System.IO.File.Copy(@"C:\Development\CustomAssembly.dll",newFileName,true);

var assembly = Assembly.LoadFrom(newFileName);
var type = assembly.GetType("CustomAssembly.DummyClass");   
#>
<#=newFileName#>
<#=type#>


来源:https://stackoverflow.com/questions/1856885/how-do-you-use-net-reflection-with-t4

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