技术开发 频道

告别重复!巧用Visual Studio代码生成器

  注意到什么了吗?生成的每个属性中,没有指定数据的类型,下面我们改进下,代码如下:

  <#+
  
private string GetCSharpType(DataRow dr)
  {
  
bool isNullable = Convert.ToBoolean(dr["AllowDBNull"]);
  
switch (dr["DataType"].ToString())
  {
  
case "System.Int16":
  
if (isNullable)
  
return"Nullable";
  
else
  
return"short";
  
case "System.Int32":
  
if (isNullable)
  
return"Nullable";
  
else
  
return "int";
  
case "System.String":
  
return "string";
  
case "System.DateTime":
  
return "DateTime";
  
case "System.Byte":
  
if (isNullable)
  
return "Nullable";
  
else
  
return "byte";
  
case "System.Byte[]":
  
return "Binary";
  
case "System.Boolean":
  
return "bool";
  
case "System.Decimal":
  
return "double";
  
case "System.Guid":
  
return "Guid";
  
default:
  
throw new Exception("Type not known");
  }
  }
  #
>

  这里,请注意我们另外编写了一个函数方法GetCSharpType,传入的参数是数据库表中的每一列,然后在代码中,根据每个数据表列的类型进行转换为C#中的语言类型。在T4模版中,注意我们使用“<#+ …#>”,在其中可以写相关的模版转换函数。

  最后,修改下调用模版函数的一句代码如下:

Write(" public " + GetCSharpType(dr) + " " + dr["ColumnName"] + " { get; set; }" + Environment.NewLine);

  以上实际生成的代码如下图:

  小 结:

  Visual Studio 2010中的T4代码模版生成器,功能是十分强大的,开发者可以结合已有的常用代码,使用T4进行编写模版,就可以很快地生成相关开发语言(C#,VB.NET)的代码,大大减轻了重复劳动,开始学习T4的编写方法可能会有点麻烦,但当开发者熟练后,就会发现T4的确大大增强了开发效率,更多的关于T4代码生成器的文档,请参考微软的相关文档。

0
相关文章