2013-04-24 35 views
10

我想獲取我的項目中使用T4/EnvDTE使用MyAttribute修飾的所有公共方法的列表。使用T4/EnvDTE獲取使用特定屬性修飾的所有方法

我知道這可以通過反射來完成,但我不想加載程序集並在T4模板中反映它,相反,我想使用現有的代碼文件作爲源代碼。

以下是樣板代碼我是獲取對當前項目的引用

<#@ template debug="true" hostspecific="true" language="C#" #> 
<#@ assembly name="EnvDTE" #> 
<#@ assembly name="System.Core.dll" #> 
<#@ import namespace="System.Linq" #> 
<#@ import namespace="System.Collections.Generic" #> 
<#@ import namespace="System.IO" #> 
<#@ output extension=".cs" #> 

<# 
    IServiceProvider _ServiceProvider = (IServiceProvider)Host; 
    if (_ServiceProvider == null) 
     throw new Exception("Host property returned unexpected value (null)"); 

    EnvDTE.DTE dte = (EnvDTE.DTE)_ServiceProvider.GetService(typeof(EnvDTE.DTE)); 
    if (dte == null) 
     throw new Exception("Unable to retrieve EnvDTE.DTE"); 

    Array activeSolutionProjects = (Array)dte.ActiveSolutionProjects; 
    if (activeSolutionProjects == null) 
     throw new Exception("DTE.ActiveSolutionProjects returned null"); 

    EnvDTE.Project dteProject = (EnvDTE.Project)activeSolutionProjects.GetValue(0); 
    if (dteProject == null) 
     throw new Exception("DTE.ActiveSolutionProjects[0] returned null"); 

#> 

回答

13

我想確認你計劃使用EnvDTE獲得有關項目的課程設計時信息,並在互聯網上找到方法。在我看來,它比冒着反映過時的同一個項目集合的風險更可靠。

既然你已經得到了你的解決方案的當前項目,你現在應該使用Visual Studio CodeModel迭代你的類和他們的方法等等。我知道這可能很煩人,但我發現一個免費的可重用的.ttinclude模板,爲您提供方法簡化了對CodeModel的訪問。你可能想看看tangible's T4 Editor。它是免費的,並附帶一個免費的模板庫,其中包含一個名爲「有形的Visual Studio自動化助手」的名爲。使用此模板,您的結果代碼可能如下所示:

<# 
// 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<EnvDTE.CodeAttribute>() 
         .Any(att => att.FullName == "System.ObsoleteAttribute")) 
     { 
     #><#= function.FullName #> 
<#   
     } 
    } 
} 
#> 
+0

我在VS的模板列表中看不到'有形的Visual Studio Automation Helper'。 – Omar 2013-04-25 14:24:02

+0

我現在看到它。你必須打開一個'.tt'文件,此時將出現一個帶有標準菜單的有形T4菜單。這是第一個菜單項。讓我給這個鏡頭。 – Omar 2013-04-25 14:36:23

+2

我可以在模板Gallary中看到Visual Studio Automation Helper,但在任何地方都沒有對VisualStudioHelper的引用。有一個名爲DteHelper的類,但它的鼻涕具有您的示例中指出的方法,例如GetAllCodeElementsOfType。 – 2013-06-30 12:15:53

相關問題