使用T4 / EnvDTE获取使用特定属性修饰的所有方法

我想获得我的项目中使用T4 / EnvDTE使用MyAttribute修饰的所有公共方法的列表。

我知道这可以通过reflection完成,但我不想加载程序集并在T4模板中反映它,而是我想使用现有的代码文件作为源代码。

以下是我在互联网上找到的样板代码,它获取对当前项目的引用

         

我想确认您使用EnvDTE获取有关项目类和方法的设计时信息的计划。 在我看来,它比冒险反映同一个项目的过时组件更可靠。

由于您已经获得了解决方案的当前项目,因此您现在应该使用Visual Studio CodeModel来迭代您的类及其方法等。我知道这可能非常烦人,但我找到了一个免费的可重用.ttinclude模板,它为您提供了方法缓动访问CodeModel。 您可能想查看有形的T4编辑器 。 它是免费的,附带一个免费的模板库,其中包含一个名为“有形的Visual Studio Automation Helper”。 使用此模板,您生成的代码可能如下所示:

 <# // get a reference to the project of this t4 template var project = VisualStudioHelper.CurrentProject; // get all class items from the code model var allClasses = VisualStudioHelper.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false); // iterate all classes foreach(EnvDTE.CodeClass codeClass in allClasses) { // get all methods implemented by this class var allFunctions = VisualStudioHelper.GetAllCodeElementsOfType(codeClass.Members, EnvDTE.vsCMElement.vsCMElementFunction, false); foreach(EnvDTE.CodeFunction function in allFunctions) { // get all attributes this method is decorated with var allAttributes = VisualStudioHelper.GetAllCodeElementsOfType(function.Attributes, vsCMElement.vsCMElementAttribute, false); // check if the System.ObsoleteAttribute is present if (allAttributes.OfType() .Any(att => att.FullName == "System.ObsoleteAttribute")) { #><#= function.FullName #> <# } } } #>