T4运行时模板

可以通过Visual Studio运行时文本模板在您的应用程序在运行时生成文本字符串。 执行应用程序的计算机不必具有 Visual Studio。 运行库模板有时称为"预处理文本模板"由于在编译时,该模板会生成运行时执行的代码。

将现有文件转换为运行时模板:

  • 将该文件的“自定义工具”属性设置为 TextTemplatingFilePreprocessor。【文本模板的自定义工具是TextTemplatingFileGenerator
  • 在文件开头插入下面的行 <#@ template language="C#" #> 

运行时模板的tt的内容如下:

 1 <#@ template language="C#" #>
 2 <#@ assembly name="System.Core" #> 
 3 <#@ import namespace="System.Linq" #>
 4 <#@ import namespace="System.Text" #>
 5 <#@ import namespace="System.Collections.Generic" #>
 6 
 7 <h2>Sales figures</h2>
 8 <table>
 9 <# foreach (var item in m_data) 
10    // m_data is declared in MyWebPageCode.cs
11    { #>
12       <tr><td> <#= item.Key #> </td>
13           <td> <#= item.Value #> </td></tr>
14 <# } // end of foreach
15 #>
16 </table>
View Code

效果如下:

  1 // ------------------------------------------------------------------------------
  2 // <auto-generated>
  3 //     此代码由工具生成。
  4 //     运行时版本: 12.0.0.0
  5 //  
  6 //     对此文件的更改可能会导致不正确的行为。此外,如果
  7 //     重新生成代码,这些更改将会丢失。
  8 // </auto-generated>
  9 // ------------------------------------------------------------------------------
 10 namespace Test
 11 {
 12     using System.Linq;
 13     using System.Text;
 14     using System.Collections.Generic;
 15     using System;
 16     
 17     /// <summary>
 18     /// Class to produce the template output
 19     /// </summary>
 20     
 21     #line 1 "F:studyshareTesthtml.tt"
 22     [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "12.0.0.0")]
 23     public partial class html : htmlBase
 24     {
 25 #line hidden
 26         /// <summary>
 27         /// Create the template output
 28         /// </summary>
 29         public virtual string TransformText()
 30         {
 31             this.Write("<table>
    ");
 32             
 33             #line 7 "F:studyshareTesthtml.tt"
 34  for (int i = 1; i <= 10; i++)
 35        { 
 36             
 37             #line default
 38             #line hidden
 39             this.Write("         <tr><td>Test name ");
 40             
 41             #line 9 "F:studyshareTesthtml.tt"
 42             this.Write(this.ToStringHelper.ToStringWithCulture(i));
 43             
 44             #line default
 45             #line hidden
 46             this.Write(" </td>
             <td>Test value ");
 47             
 48             #line 10 "F:studyshareTesthtml.tt"
 49             this.Write(this.ToStringHelper.ToStringWithCulture(i * i));
 50             
 51             #line default
 52             #line hidden
 53             this.Write(" </td> </tr>
    ");
 54             
 55             #line 11 "F:studyshareTesthtml.tt"
 56  } 
 57             
 58             #line default
 59             #line hidden
 60             this.Write(" </table>");
 61             return this.GenerationEnvironment.ToString();
 62         }
 63     }
 64     
 65     #line default
 66     #line hidden
 67     #region Base class
 68     /// <summary>
 69     /// Base class for this transformation
 70     /// </summary>
 71     [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "12.0.0.0")]
 72     public class htmlBase
 73     {
 74         #region Fields
 75         private global::System.Text.StringBuilder generationEnvironmentField;
 76         private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
 77         private global::System.Collections.Generic.List<int> indentLengthsField;
 78         private string currentIndentField = "";
 79         private bool endsWithNewline;
 80         private global::System.Collections.Generic.IDictionary<string, object> sessionField;
 81         #endregion
 82         #region Properties
 83         /// <summary>
 84         /// The string builder that generation-time code is using to assemble generated output
 85         /// </summary>
 86         protected System.Text.StringBuilder GenerationEnvironment
 87         {
 88             get
 89             {
 90                 if ((this.generationEnvironmentField == null))
 91                 {
 92                     this.generationEnvironmentField = new global::System.Text.StringBuilder();
 93                 }
 94                 return this.generationEnvironmentField;
 95             }
 96             set
 97             {
 98                 this.generationEnvironmentField = value;
 99             }
100         }
101         /// <summary>
102         /// The error collection for the generation process
103         /// </summary>
104         public System.CodeDom.Compiler.CompilerErrorCollection Errors
105         {
106             get
107             {
108                 if ((this.errorsField == null))
109                 {
110                     this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
111                 }
112                 return this.errorsField;
113             }
114         }
115         /// <summary>
116         /// A list of the lengths of each indent that was added with PushIndent
117         /// </summary>
118         private System.Collections.Generic.List<int> indentLengths
119         {
120             get
121             {
122                 if ((this.indentLengthsField == null))
123                 {
124                     this.indentLengthsField = new global::System.Collections.Generic.List<int>();
125                 }
126                 return this.indentLengthsField;
127             }
128         }
129         /// <summary>
130         /// Gets the current indent we use when adding lines to the output
131         /// </summary>
132         public string CurrentIndent
133         {
134             get
135             {
136                 return this.currentIndentField;
137             }
138         }
139         /// <summary>
140         /// Current transformation session
141         /// </summary>
142         public virtual global::System.Collections.Generic.IDictionary<string, object> Session
143         {
144             get
145             {
146                 return this.sessionField;
147             }
148             set
149             {
150                 this.sessionField = value;
151             }
152         }
153         #endregion
154         #region Transform-time helpers
155         /// <summary>
156         /// Write text directly into the generated output
157         /// </summary>
158         public void Write(string textToAppend)
159         {
160             if (string.IsNullOrEmpty(textToAppend))
161             {
162                 return;
163             }
164             // If we're starting off, or if the previous text ended with a newline,
165             // we have to append the current indent first.
166             if (((this.GenerationEnvironment.Length == 0) 
167                         || this.endsWithNewline))
168             {
169                 this.GenerationEnvironment.Append(this.currentIndentField);
170                 this.endsWithNewline = false;
171             }
172             // Check if the current text ends with a newline
173             if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
174             {
175                 this.endsWithNewline = true;
176             }
177             // This is an optimization. If the current indent is "", then we don't have to do any
178             // of the more complex stuff further down.
179             if ((this.currentIndentField.Length == 0))
180             {
181                 this.GenerationEnvironment.Append(textToAppend);
182                 return;
183             }
184             // Everywhere there is a newline in the text, add an indent after it
185             textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
186             // If the text ends with a newline, then we should strip off the indent added at the very end
187             // because the appropriate indent will be added when the next time Write() is called
188             if (this.endsWithNewline)
189             {
190                 this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
191             }
192             else
193             {
194                 this.GenerationEnvironment.Append(textToAppend);
195             }
196         }
197         /// <summary>
198         /// Write text directly into the generated output
199         /// </summary>
200         public void WriteLine(string textToAppend)
201         {
202             this.Write(textToAppend);
203             this.GenerationEnvironment.AppendLine();
204             this.endsWithNewline = true;
205         }
206         /// <summary>
207         /// Write formatted text directly into the generated output
208         /// </summary>
209         public void Write(string format, params object[] args)
210         {
211             this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
212         }
213         /// <summary>
214         /// Write formatted text directly into the generated output
215         /// </summary>
216         public void WriteLine(string format, params object[] args)
217         {
218             this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
219         }
220         /// <summary>
221         /// Raise an error
222         /// </summary>
223         public void Error(string message)
224         {
225             System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
226             error.ErrorText = message;
227             this.Errors.Add(error);
228         }
229         /// <summary>
230         /// Raise a warning
231         /// </summary>
232         public void Warning(string message)
233         {
234             System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
235             error.ErrorText = message;
236             error.IsWarning = true;
237             this.Errors.Add(error);
238         }
239         /// <summary>
240         /// Increase the indent
241         /// </summary>
242         public void PushIndent(string indent)
243         {
244             if ((indent == null))
245             {
246                 throw new global::System.ArgumentNullException("indent");
247             }
248             this.currentIndentField = (this.currentIndentField + indent);
249             this.indentLengths.Add(indent.Length);
250         }
251         /// <summary>
252         /// Remove the last indent that was added with PushIndent
253         /// </summary>
254         public string PopIndent()
255         {
256             string returnValue = "";
257             if ((this.indentLengths.Count > 0))
258             {
259                 int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
260                 this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
261                 if ((indentLength > 0))
262                 {
263                     returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
264                     this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
265                 }
266             }
267             return returnValue;
268         }
269         /// <summary>
270         /// Remove any indentation
271         /// </summary>
272         public void ClearIndent()
273         {
274             this.indentLengths.Clear();
275             this.currentIndentField = "";
276         }
277         #endregion
278         #region ToString Helpers
279         /// <summary>
280         /// Utility class to produce culture-oriented representation of an object as a string.
281         /// </summary>
282         public class ToStringInstanceHelper
283         {
284             private System.IFormatProvider formatProviderField  = global::System.Globalization.CultureInfo.InvariantCulture;
285             /// <summary>
286             /// Gets or sets format provider to be used by ToStringWithCulture method.
287             /// </summary>
288             public System.IFormatProvider FormatProvider
289             {
290                 get
291                 {
292                     return this.formatProviderField ;
293                 }
294                 set
295                 {
296                     if ((value != null))
297                     {
298                         this.formatProviderField  = value;
299                     }
300                 }
301             }
302             /// <summary>
303             /// This is called from the compile/run appdomain to convert objects within an expression block to a string
304             /// </summary>
305             public string ToStringWithCulture(object objectToConvert)
306             {
307                 if ((objectToConvert == null))
308                 {
309                     throw new global::System.ArgumentNullException("objectToConvert");
310                 }
311                 System.Type t = objectToConvert.GetType();
312                 System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
313                             typeof(System.IFormatProvider)});
314                 if ((method == null))
315                 {
316                     return objectToConvert.ToString();
317                 }
318                 else
319                 {
320                     return ((string)(method.Invoke(objectToConvert, new object[] {
321                                 this.formatProviderField })));
322                 }
323             }
324         }
325         private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
326         /// <summary>
327         /// Helper to produce culture-oriented representation of an object as a string
328         /// </summary>
329         public ToStringInstanceHelper ToStringHelper
330         {
331             get
332             {
333                 return this.toStringHelperField;
334             }
335         }
336         #endregion
337     }
338     #endregion
339 }
View Code
 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             html html = new html();
 6             System.IO.File.WriteAllText("outputPage.html", html.TransformText()); 
 7             Console.ReadKey();
 8         }  
 9        
10     }
11 结果:
12 
13 <table>
14              <tr><td>Test name 1 </td>
15              <td>Test value 1 </td> </tr>
16              <tr><td>Test name 2 </td>
17              <td>Test value 4 </td> </tr>
18              <tr><td>Test name 3 </td>
19              <td>Test value 9 </td> </tr>
20              <tr><td>Test name 4 </td>
21              <td>Test value 16 </td> </tr>
22              <tr><td>Test name 5 </td>
23              <td>Test value 25 </td> </tr>
24              <tr><td>Test name 6 </td>
25              <td>Test value 36 </td> </tr>
26              <tr><td>Test name 7 </td>
27              <td>Test value 49 </td> </tr>
28              <tr><td>Test name 8 </td>
29              <td>Test value 64 </td> </tr>
30              <tr><td>Test name 9 </td>
31              <td>Test value 81 </td> </tr>
32              <tr><td>Test name 10 </td>
33              <td>Test value 100 </td> </tr>
34      </table>
View Code

若要在特定命名空间中放置已生成的类,请设置文本模板文件的“自定义工具命名空间”属性。

如果希望模板代码引用 .NET 或其他程序集(如 System.Xml.dll),应以常规方式将其添加到项目的“引用”中。

如果要以与 using 语句相同的方式导入命名空间,可以使用 import 指令

<#@ import namespace="System.Xml" #>

 如果要在几个模板间共享文本,可以将文本放置在一个单独的文件中,然后在需要这些文本的每个文件中包含这些文本:

<#@include file="CommonHeader.txt" #> 

继承模式:基方法中的片段

  • 基类在类功能块<#+...#>中定义方法
  • 派生类可以调用基类中定义的方法 

MyTextTemplate1.tt继承自SharedFragments.tt(生成的类MyTextTemplate1.cs 继承自SharedFragments.cs)

  1 SharedFragments.tt
  2 <#@ template language="C#" #>
  3 <#@ assembly name="System.Core" #>
  4 <#@ import namespace="System.Linq" #>
  5 <#@ import namespace="System.Text" #>
  6 <#@ import namespace="System.Collections.Generic" #>
  7  
  8 <#+
  9 protected void SharedText(int n)
 10 {
 11 #>
 12    Shared Text <#= n #>
 13 <#+
 14 }
 15 // Insert more methods here if required.
 16 #>
 17 
 18 SharedFragments.cs
 19 // ------------------------------------------------------------------------------
 20 // <auto-generated>
 21 //     此代码由工具生成。
 22 //     运行时版本: 12.0.0.0
 23 //  
 24 //     对此文件的更改可能会导致不正确的行为。此外,如果
 25 //     重新生成代码,这些更改将会丢失。
 26 // </auto-generated>
 27 // ------------------------------------------------------------------------------
 28 namespace Test
 29 {
 30     using System.Linq;
 31     using System.Text;
 32     using System.Collections.Generic;
 33     using System;
 34     
 35     /// <summary>
 36     /// Class to produce the template output
 37     /// </summary>
 38     
 39     #line 1 "F:studyshareTestSharedFragments.tt"
 40     [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "12.0.0.0")]
 41     public partial class SharedFragments : SharedFragmentsBase
 42     {
 43 #line hidden
 44         /// <summary>
 45         /// Create the template output
 46         /// </summary>
 47         public virtual string TransformText()
 48         {
 49             this.Write(" 
");
 50             return this.GenerationEnvironment.ToString();
 51         }
 52         
 53         #line 7 "F:studyshareTestSharedFragments.tt"
 54 
 55 protected void SharedText(int n)
 56 {
 57 
 58         
 59         #line default
 60         #line hidden
 61         
 62         #line 10 "F:studyshareTestSharedFragments.tt"
 63 this.Write("   Shared Text ");
 64 
 65         
 66         #line default
 67         #line hidden
 68         
 69         #line 11 "F:studyshareTestSharedFragments.tt"
 70 this.Write(this.ToStringHelper.ToStringWithCulture(n));
 71 
 72         
 73         #line default
 74         #line hidden
 75         
 76         #line 11 "F:studyshareTestSharedFragments.tt"
 77 this.Write("
");
 78 
 79         
 80         #line default
 81         #line hidden
 82         
 83         #line 12 "F:studyshareTestSharedFragments.tt"
 84 
 85 }
 86 // Insert more methods here if required.
 87 
 88         
 89         #line default
 90         #line hidden
 91     }
 92     
 93     #line default
 94     #line hidden
 95     #region Base class
 96     /// <summary>
 97     /// Base class for this transformation
 98     /// </summary>
 99     [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "12.0.0.0")]
100     public class SharedFragmentsBase
101     {
102         #region Fields
103         private global::System.Text.StringBuilder generationEnvironmentField;
104         private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
105         private global::System.Collections.Generic.List<int> indentLengthsField;
106         private string currentIndentField = "";
107         private bool endsWithNewline;
108         private global::System.Collections.Generic.IDictionary<string, object> sessionField;
109         #endregion
110         #region Properties
111         /// <summary>
112         /// The string builder that generation-time code is using to assemble generated output
113         /// </summary>
114         protected System.Text.StringBuilder GenerationEnvironment
115         {
116             get
117             {
118                 if ((this.generationEnvironmentField == null))
119                 {
120                     this.generationEnvironmentField = new global::System.Text.StringBuilder();
121                 }
122                 return this.generationEnvironmentField;
123             }
124             set
125             {
126                 this.generationEnvironmentField = value;
127             }
128         }
129         /// <summary>
130         /// The error collection for the generation process
131         /// </summary>
132         public System.CodeDom.Compiler.CompilerErrorCollection Errors
133         {
134             get
135             {
136                 if ((this.errorsField == null))
137                 {
138                     this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
139                 }
140                 return this.errorsField;
141             }
142         }
143         /// <summary>
144         /// A list of the lengths of each indent that was added with PushIndent
145         /// </summary>
146         private System.Collections.Generic.List<int> indentLengths
147         {
148             get
149             {
150                 if ((this.indentLengthsField == null))
151                 {
152                     this.indentLengthsField = new global::System.Collections.Generic.List<int>();
153                 }
154                 return this.indentLengthsField;
155             }
156         }
157         /// <summary>
158         /// Gets the current indent we use when adding lines to the output
159         /// </summary>
160         public string CurrentIndent
161         {
162             get
163             {
164                 return this.currentIndentField;
165             }
166         }
167         /// <summary>
168         /// Current transformation session
169         /// </summary>
170         public virtual global::System.Collections.Generic.IDictionary<string, object> Session
171         {
172             get
173             {
174                 return this.sessionField;
175             }
176             set
177             {
178                 this.sessionField = value;
179             }
180         }
181         #endregion
182         #region Transform-time helpers
183         /// <summary>
184         /// Write text directly into the generated output
185         /// </summary>
186         public void Write(string textToAppend)
187         {
188             if (string.IsNullOrEmpty(textToAppend))
189             {
190                 return;
191             }
192             // If we're starting off, or if the previous text ended with a newline,
193             // we have to append the current indent first.
194             if (((this.GenerationEnvironment.Length == 0) 
195                         || this.endsWithNewline))
196             {
197                 this.GenerationEnvironment.Append(this.currentIndentField);
198                 this.endsWithNewline = false;
199             }
200             // Check if the current text ends with a newline
201             if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
202             {
203                 this.endsWithNewline = true;
204             }
205             // This is an optimization. If the current indent is "", then we don't have to do any
206             // of the more complex stuff further down.
207             if ((this.currentIndentField.Length == 0))
208             {
209                 this.GenerationEnvironment.Append(textToAppend);
210                 return;
211             }
212             // Everywhere there is a newline in the text, add an indent after it
213             textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
214             // If the text ends with a newline, then we should strip off the indent added at the very end
215             // because the appropriate indent will be added when the next time Write() is called
216             if (this.endsWithNewline)
217             {
218                 this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
219             }
220             else
221             {
222                 this.GenerationEnvironment.Append(textToAppend);
223             }
224         }
225         /// <summary>
226         /// Write text directly into the generated output
227         /// </summary>
228         public void WriteLine(string textToAppend)
229         {
230             this.Write(textToAppend);
231             this.GenerationEnvironment.AppendLine();
232             this.endsWithNewline = true;
233         }
234         /// <summary>
235         /// Write formatted text directly into the generated output
236         /// </summary>
237         public void Write(string format, params object[] args)
238         {
239             this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
240         }
241         /// <summary>
242         /// Write formatted text directly into the generated output
243         /// </summary>
244         public void WriteLine(string format, params object[] args)
245         {
246             this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
247         }
248         /// <summary>
249         /// Raise an error
250         /// </summary>
251         public void Error(string message)
252         {
253             System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
254             error.ErrorText = message;
255             this.Errors.Add(error);
256         }
257         /// <summary>
258         /// Raise a warning
259         /// </summary>
260         public void Warning(string message)
261         {
262             System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
263             error.ErrorText = message;
264             error.IsWarning = true;
265             this.Errors.Add(error);
266         }
267         /// <summary>
268         /// Increase the indent
269         /// </summary>
270         public void PushIndent(string indent)
271         {
272             if ((indent == null))
273             {
274                 throw new global::System.ArgumentNullException("indent");
275             }
276             this.currentIndentField = (this.currentIndentField + indent);
277             this.indentLengths.Add(indent.Length);
278         }
279         /// <summary>
280         /// Remove the last indent that was added with PushIndent
281         /// </summary>
282         public string PopIndent()
283         {
284             string returnValue = "";
285             if ((this.indentLengths.Count > 0))
286             {
287                 int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
288                 this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
289                 if ((indentLength > 0))
290                 {
291                     returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
292                     this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
293                 }
294             }
295             return returnValue;
296         }
297         /// <summary>
298         /// Remove any indentation
299         /// </summary>
300         public void ClearIndent()
301         {
302             this.indentLengths.Clear();
303             this.currentIndentField = "";
304         }
305         #endregion
306         #region ToString Helpers
307         /// <summary>
308         /// Utility class to produce culture-oriented representation of an object as a string.
309         /// </summary>
310         public class ToStringInstanceHelper
311         {
312             private System.IFormatProvider formatProviderField  = global::System.Globalization.CultureInfo.InvariantCulture;
313             /// <summary>
314             /// Gets or sets format provider to be used by ToStringWithCulture method.
315             /// </summary>
316             public System.IFormatProvider FormatProvider
317             {
318                 get
319                 {
320                     return this.formatProviderField ;
321                 }
322                 set
323                 {
324                     if ((value != null))
325                     {
326                         this.formatProviderField  = value;
327                     }
328                 }
329             }
330             /// <summary>
331             /// This is called from the compile/run appdomain to convert objects within an expression block to a string
332             /// </summary>
333             public string ToStringWithCulture(object objectToConvert)
334             {
335                 if ((objectToConvert == null))
336                 {
337                     throw new global::System.ArgumentNullException("objectToConvert");
338                 }
339                 System.Type t = objectToConvert.GetType();
340                 System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
341                             typeof(System.IFormatProvider)});
342                 if ((method == null))
343                 {
344                     return objectToConvert.ToString();
345                 }
346                 else
347                 {
348                     return ((string)(method.Invoke(objectToConvert, new object[] {
349                                 this.formatProviderField })));
350                 }
351             }
352         }
353         private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
354         /// <summary>
355         /// Helper to produce culture-oriented representation of an object as a string
356         /// </summary>
357         public ToStringInstanceHelper ToStringHelper
358         {
359             get
360             {
361                 return this.toStringHelperField;
362             }
363         }
364         #endregion
365     }
366     #endregion
367 }
View Code
 1 MyTextTemplate1.tt
 2 <#@ template language="C#" inherits="SharedFragments" #>
 3 begin 1
 4     <#SharedText(2) ;#>
 5 end 1
 6 
 7 
 8 MyTextTemplate1.cs
 9 // ------------------------------------------------------------------------------
10 // <auto-generated>
11 //     此代码由工具生成。
12 //     运行时版本: 12.0.0.0
13 //  
14 //     对此文件的更改可能会导致不正确的行为。此外,如果
15 //     重新生成代码,这些更改将会丢失。
16 // </auto-generated>
17 // ------------------------------------------------------------------------------
18 namespace Test
19 {
20     using System;
21     
22     /// <summary>
23     /// Class to produce the template output
24     /// </summary>
25     
26     #line 1 "F:studyshareTestMyTextTemplate1.tt"
27     [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "12.0.0.0")]
28     public partial class MyTextTemplate1 : SharedFragments
29     {
30 #line hidden
31         /// <summary>
32         /// Create the template output
33         /// </summary>
34         public override string TransformText()
35         {
36             this.Write("begin 1
    ");
37             
38             #line 3 "F:studyshareTestMyTextTemplate1.tt"
39 SharedText(2) ;
40             
41             #line default
42             #line hidden
43             this.Write("end 1
");
44             return this.GenerationEnvironment.ToString();
45         }
46     }
47     
48     #line default
49     #line hidden
50 }
View Code

使用 T4 文本模板的运行时文本生成

原文地址:https://www.cnblogs.com/goodlucklzq/p/4425162.html