2016-12-20 38 views
0

我正在嘗試在T4模板中編寫一個類。它給人的錯誤:T4模板:名稱空間上的錯誤

Compiling transofrmation: Type of namespace definition, or end-of-file expected 

,如果我有以下代碼:

<#+ 
namespace Learn { 
    public class Converter 
    { 

    } 
} 
#> 

但如果我刪除命名空間

<#+ 
    public class Converter 
    { 

    } 
#> 

我的問題是,爲什麼T4不正常工作承認namespace

+1

因爲'<# #>'內的代碼不是正在生成的代碼,而是正在運行的代碼以生成代碼。 – Pawel

回答

2

<#+#>是一個類特徵塊。你放在這個塊內的任何東西都會寫在類聲明中。當您添加一個命名空間T4將生成並嘗試編譯是這樣的:

class MyT4TempGen { 

    public string run() { 
      inside here is code that uses a string builder to build up all your <# #> tags into one big statement 
    } 

    from here down all your <#+ #> tags are added 

    namespace Learn { 
     public class Converter { 

     } 
    } 

} 

這不是有效的C#代碼,名稱空間不能在一個類語句中存在。當你這樣做沒有命名空間,你會得到這樣的:

class MyT4TempGen { 

    public string run() { 
     inside here is code that uses a string builder to build up all your <# #> tags into one big statement 
    } 

    from here down all your <#+ #> tags are added   

    public class Converter { 

    } 

} 

這是有效的C#代碼,你的類將是一個子類中的一個T4編譯器創建的。

以下是msdn docs的鏈接,說明支持的標籤。請參閱「類功能控制塊」一節。只要記住,無論您輸入到tt或t4文件中,都將被解析並轉換爲.net代碼,因此您必須遵循所有正常的語法規則。

+0

謝謝弗蘭克的詳細解釋,這解釋了一些事情。 – akshayKhot

相關問題