文字範本公用程式方法

當您在 Visual Studio 文字範本中撰寫程式碼時,有數種方法永遠都可供您使用。 TextTransformation 中定義這些方法。

提示

您也可以在一般 (未預處理的) 文字範本中使用主機環境提供的其他方法和服務。 例如,您可以解析檔案路徑、記錄錯誤,以及取得 Visual Studio 所提供的服務,以及任何載入的封裝。 如需詳細資訊,請參閱從文字範本存取 Visual Studio

撰寫方法

您可以使用 Write()WriteLine() 方法在標準程式碼區塊內附加文字,而不是使用運算式程式碼區塊。 下列兩個程式碼區塊的功能相同。

具有運算式區塊的程式碼區塊

<#
int i = 10;
while (i-- > 0)
    { #>
        <#= i #>
    <# }
#>

使用 WriteLine() 的程式碼區塊

<#
    int i = 10;
    while (i-- > 0)
    {
        WriteLine((i.ToString()));
    }
#>

您可能會發現使用其中一個公用程式方法,而不是在具有巢狀控制結構的長程式碼區塊內使用運算式區塊很實用。

Write()WriteLine() 方法有兩個多載,一個採用單一字串參數,另一個採用複合格式字串加上要包含在字串中的物件陣列 (例如 Console.WriteLine() 方法)。 下列兩個 WriteLine() 用法的功能相同:

<#
    string msg = "Say: {0}, {1}, {2}";
    string s1 = "hello";
    string s2 = "goodbye";
    string s3 = "farewell";

    WriteLine(msg, s1, s2, s3);
    WriteLine("Say: hello, goodbye, farewell");
#>

縮排方法

您可以使用縮排方法來格式化文字範本的輸出。 TextTransformation 類別具有 CurrentIndent 字串屬性,顯示文字範本中目前的縮排,以及已新增之縮排清單的 indentLengths 欄位。 您可以使用 PushIndent() 方法增加縮排,並使用 PopIndent() 方法減去縮排。 如果您想要移除所有縮排,請使用 ClearIndent() 方法。 下列程式碼區塊顯示這些方法的用法:

<#
    WriteLine(CurrentIndent + "Hello");
    PushIndent("    ");
    WriteLine(CurrentIndent + "Hello");
    PushIndent("    ");
    WriteLine(CurrentIndent + "Hello");
    ClearIndent();
    WriteLine(CurrentIndent + "Hello");
    PushIndent("    ");
    WriteLine(CurrentIndent + "Hello");
#>

此程式碼區塊會產生下列輸出:

Hello
        Hello
                Hello
Hello
        Hello

錯誤和警告方法

您可以使用錯誤和警告公用程式方法,將訊息新增至 Visual Studio 錯誤清單。 例如,下列程式碼會將錯誤訊息新增至錯誤清單。

<#
  try
  {
    string str = null;
    Write(str.Length.ToString());
  }
  catch (Exception e)
  {
    Error(e.Message);
  }
#>

存取主機和服務提供者

屬性 this.Host 可以提供執行範本之主機所公開屬性的存取權。 若要使用 this.Host,您必須在 <@template#> 指示詞中設定 hostspecific 屬性:

<#@template ... hostspecific="true" #>

this.Host 的類型取決於範本執行所在的主機類型。 在於 Visual Studio 中執行的範本中,您可以將 this.Host 轉換成 IServiceProvider,以取得 IDE 等服務的存取權。 例如:

EnvDTE.DTE dte = (EnvDTE.DTE) ((IServiceProvider) this.Host)
                       .GetService(typeof(EnvDTE.DTE));

使用不同組的公用程式方法

在產生文字的過程中,您的範本檔案會轉換成類別,該類別一律會命名為 GeneratedTextTransformation,並繼承自 TextTransformation。 如果您想要改用一組不同的方法,可以撰寫自己的類別,並在範本指示詞中指定。 您的類別必須繼承自 TextTransformation

<#@ template inherits="MyUtilityClass" #>

使用 assembly 指示詞來參考可找到已編譯類別的組件。