有的时候,我们需要定义一些Enum类型,一种比较灵活的做法是用T4模板去读取指定的XML,然后根据NODE生成我们想到的Enum类型。首先看,我们有这样一个XML文件:


1:  <?xml version="1.0" encoding="utf-8" ?>
2:  <Root>
3:    <Element Name="Red"/>
4:    <Element Name="Blue" />
5:  </Root>


然后我们编写扩展名为TT的模板文件在VisualStudio中:


1:  <#@ template language="C#"  hostspecific="True"#>
2:  <#@ assembly name="System.Core" #>
3:  <#@ assembly name="System.Xml" #>
4:  <#@ import namespace="System.Xml" #>
5:  <#@ import namespace="System.Collections.Generic" #>
6:  <#@ import namespace="System.IO" #>
7:  using System;
8:
9:  namespace Examples
10:  {
11:      public class ExampleClass
12:      {
13:          #region Enums
14:
15:          public enum MyExampleEnum
16:          {
17:  <#
18:      foreach (string name in this.GetNames())
19:      {
20:  #>
21:              <#= name #>,
22:  <#
23:      }
24:          #>
25:          }
26:
27:          #endregion
28:      }
29:  }
30:  <#+
31:      public List<string> GetNames()
32:      {
33:          List<string> result = new List<string>();
34:          XmlDocument doc = new XmlDocument();
35:          string absolutePath = Host.ResolvePath("MyEnum.xml");
36:          doc.Load(absolutePath);
37:          foreach (XmlNode node in doc.SelectNodes("/Root/Element"))
38:          {
39:              result.Add(node.Attributes["Name"].InnerText);
40:          }
41:          return result;
42:      }
43:  #>


最后执行这个模板文件,将会在当前目录下,生成如下的CODE文件:


1:  using System;
2:
3:  namespace Examples
4:  {
5:      public class ExampleClass
6:      {
7:          #region Enums
8:
9:          public enum MyExampleEnum
10:          {
11:              Red,
12:              Blue,
13:          }
14:
15:          #endregion
16:      }
17:  }


是不是很简单,当然你可以编写更加复杂的模板文件,生成你想到CODE。