服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#如何通过T4自动生成代码详解

C#如何通过T4自动生成代码详解

2022-03-02 14:24FreeTimeWorker C#

这篇文章主要给大家介绍了关于C#如何通过T4自动生成代码的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用c#具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

T4简介

T4(Text Template Transformation Toolkit)在 Visual Studio 中,“T4 文本模板”是由一些文本块和控制逻辑组成的混合模板,它可以生成文本文件。 在 Visual C# 或 Visual Basic 中,控制逻辑编写为程序代码的片段。生成的文件可以是任何类型的文本,例如网页、资源文件或任何语言的程序源代码。

T4 文本模板有两种类型:

1、运行时模板

可在应用程序中执行运行时 T4 文本模板(“预处理过的”模板)以便生成文本字符串(通常作为其输出的一部分)。

若要创建运行时模板,请向您的项目中添加“已预处理的文本模板”文件。

另外,您还可以添加纯文本文件并将其“自定义工具”属性设置为“TextTemplatingFilePreprocessor”。

2、设计时模板

在 Visual Studio 中执行设计时 T4 文本模板,以便定义应用程序的部分源代码和其他资源。

通常,您可以使用读取单个输入文件或数据库中的数据的多个模板,并生成一些 .cs、.vb 或其他源文件。

每个模板都生成一个文件。 在 Visual Studio 或 MSBuild 内执行它们。

若要创建设计时模板,请向您的项目中添加“文本模板”文件。 另外,您还可以添加纯文本文件并将其“自定义工具”属性设置为“TextTemplatingFileGenerator”。

通过T4模板生成代码,运行时实现

关键代码段:Host

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
using Microsoft.VisualStudio.TextTemplating;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CodeGenerate.EngineHost
{
 public class TextTemplatingEngineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost
 {
 public List<string> LocalDlls { get; set; }
 public List<string> Namespaces { get; set; }
 /// <summary>
 /// 模板文件
 /// </summary>
 public string TemplateFile { get; set; }
 /// <summary>
 /// 文件扩展名
 /// </summary>
 public string FileExtension { get; set; }
 /// <summary>
 /// 文件扩展名
 /// </summary>
 public Encoding FileEncoding { get; set; }
 /// <summary>
 /// 错误信息
 /// </summary>
 public CompilerErrorCollection Errors { get; set; }
 public IList<string> StandardAssemblyReferences
 {
  get
  {
  LocalDlls.Add(typeof(System.Uri).Assembly.Location);
  return LocalDlls;
  }
 }
 public IList<string> StandardImports
 {
  get
  {
  Namespaces.Add("System");
  return Namespaces;
  }
 }
 /// <summary>
 /// 参数传递
 /// </summary>
 public ITextTemplatingSession Session { get; set; }
 
 public bool LoadIncludeText(string requestFileName, out string content, out string location)
 {
  content = System.String.Empty;
  location = System.String.Empty;
  if (File.Exists(requestFileName))
  {
  content = File.ReadAllText(requestFileName);
  return true;
  }
  else
  {
  return false;
  }
 }
 public object GetHostOption(string optionName)
 {
  object returnObject;
  switch (optionName)
  {
  case "CacheAssemblies":
   returnObject = true;
   break;
  default:
   returnObject = null;
   break;
  }
  return returnObject;
 }
 public string ResolveAssemblyReference(string assemblyReference)
 {
  if (File.Exists(assemblyReference))
  {
  return assemblyReference;
  }
  string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), assemblyReference);
  if (File.Exists(candidate))
  {
  return candidate;
  }
  return "";
 }
 public Type ResolveDirectiveProcessor(string processorName)
 {
  if (string.Compare(processorName, "XYZ", StringComparison.OrdinalIgnoreCase) == 0)
  {
  //return typeof();
  }
  throw new Exception("Directive Processor not found");
 }
 public string ResolvePath(string fileName)
 {
  if (fileName == null)
  {
  throw new ArgumentNullException("the file name cannot be null");
  }
  if (File.Exists(fileName))
  {
  return fileName;
  }
  string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), fileName);
  if (File.Exists(candidate))
  {
  return candidate;
  }
  return fileName;
 }
 public string ResolveParameterValue(string directiveId, string processorName, string parameterName)
 {
  if (directiveId == null)
  {
  throw new ArgumentNullException("the directiveId cannot be null");
  }
  if (processorName == null)
  {
  throw new ArgumentNullException("the processorName cannot be null");
  }
  if (parameterName == null)
  {
  throw new ArgumentNullException("the parameterName cannot be null");
  }
  return String.Empty;
 }
 public void SetFileExtension(string extension)
 {
  FileExtension = extension;
 }
 public void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective)
 {
  FileEncoding = encoding;
 }
 public void LogErrors(CompilerErrorCollection errors)
 {
  Errors = errors;
 }
 public AppDomain ProvideTemplatingAppDomain(string content)
 {
  return AppDomain.CreateDomain("Generation App Domain");
 }
 
 public ITextTemplatingSession CreateSession()
 {
  return this.Session;
 }
 }
}

Session

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using Microsoft.VisualStudio.TextTemplating;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
 
namespace CodeGenerate.EngineHost
{
 [Serializable]
 public class TextTemplatingSession : Dictionary<string, Object>, ITextTemplatingSession, ISerializable
 {
  public Guid Id { get;private set; }
 
  public TextTemplatingSession() : this(Guid.NewGuid())
  {
  }
 
  public TextTemplatingSession(Guid id)
  {
   this.Id = id;
  }
  public override int GetHashCode()
  {
   return Id.GetHashCode();
  }
  public TextTemplatingSession(SerializationInfo info, StreamingContext context)
   : base(info, context)
  {
   Id = (Guid)info.GetValue("Id", typeof(Guid));
  }
 
  void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
  {
   base.GetObjectData(info, context);
   info.AddValue("Id", Id);
  }
 
  public override bool Equals(object obj)
  {
   var o = obj as TextTemplatingSession;
   return o != null && o.Equals(this);
  }
 
  public bool Equals(ITextTemplatingSession other)
  {
   return other != null && other.Id == this.Id;
  }
 
  public bool Equals(Guid other)
  {
   return other.Equals(Id);
  }
 }
}

入口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
string templateFileName = "Template/test.tt";
   TextTemplatingEngineHost host = new TextTemplatingEngineHost();
   Engine engine = new Engine();
   //引入本地dll
   host.LocalDlls = new List<string>() { AppDomain.CurrentDomain.BaseDirectory.ToString() + "Params.dll" };
   //引入命名空间
   host.Namespaces = new List<string>() { "Params" };
   //模板文件
   host.TemplateFile = templateFileName;
   //设置输出文件的编码格式
   host.SetOutputEncoding(System.Text.Encoding.UTF8, false);
   //通过Session将参数传递到模板
   EngineHost.TextTemplatingSession keyValuePairs = new EngineHost.TextTemplatingSession();
   testType t = new testType() { Name = "666666666666" };
   keyValuePairs.Add("test", t);
   host.Session = keyValuePairs;
   //模板
   string input = File.ReadAllText(templateFileName);
   //执行代码生成
   string output = engine.ProcessTemplate(input, host);
   //设置文件的输出路径和文件扩展名 ,,根据模板中的设置定义
   string outputFileName = string.Concat(
    AppDomain.CurrentDomain.BaseDirectory.ToString(), "Output/",
    Path.GetFileNameWithoutExtension(templateFileName),
    host.FileExtension);
   //将生成的文件写入到新位置
   File.WriteAllText(outputFileName, output, host.FileEncoding);
   if (host.Errors.HasErrors)
   {
    foreach (CompilerError error in host.Errors)
    {
     MessageBox.Show(error.ToString());
    }
   }

tt文件

?
1
2
3
4
5
6
7
8
9
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ assembly name="Params.dll" #>
<#@ import namespace="Params" #>
<#@ parameter type="Params.testType" name="test" #>
<#@ output extension=".cs" #>
<# if(test!=null&&test.Name!=null){#>
<#=test.Name #>
<# } #>

自定义参数

?
1
2
3
4
5
[Serializable]
 public class testType
 {
  public string Name { get; set; }
 }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:https://www.cnblogs.com/zzfstudy/p/9796816.html

延伸 · 阅读

精彩推荐
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10