11

MyAttributeT4/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");

#>
4

1 に答える 1

14

EnvDTE を使用して、プロジェクトのクラスとメソッドに関する設計時の情報を取得する計画を確認したいと思います。私の意見では、同じプロジェクトの古いアセンブリを反映する危険を冒すよりも信頼性があります。

ソリューションの現在のプロジェクトを既に取得しているので、Visual Studio CodeModelを使用して、クラスとそのメソッドなどを反復処理する必要があります。これがかなり面倒なことはわかっていますが、メソッドの緩和を提供する無料の再利用可能な .ttinclude テンプレートを見つけました。 CodeModel へのアクセス。tangible の 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 #>
<#          
        }
    }
}
#>
于 2013-04-25T07:35:17.983 に答える