簡體   English   中英

使用T4 / EnvDTE獲取使用特定屬性修飾的所有方法

[英]Get all methods that are decorated with a specific attribute using T4/EnvDTE

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

我知道這可以通過反射完成,但我不想加載程序集並在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");

#>

我想確認您使用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<EnvDTE.CodeAttribute>()
                         .Any(att => att.FullName == "System.ObsoleteAttribute"))
        {
        #><#= function.FullName #>
<#          
        }
    }
}
#>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM