美文网首页
自己动手做个代码生成器(一)

自己动手做个代码生成器(一)

作者: singba | 来源:发表于2018-11-19 17:06 被阅读0次

本文以VS中的文本模板,介绍一种代码生成方法

新增文本模板文件Entity.tt(在项模板中选择"文本模板")

image.png
  • 看看文件里有什么
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".txt"  #>
  • 最后一行 output extension=".txt" 设置输出文件扩展名为.txt,我们改成.cs
    <#@ output extension=".cs" #>
  • 保存文件(ctrl+s),可以看到项目里文件已经修改为Entity.cs


    image.png
  • 这时候打开Entity.cs文件,还是什么都没有,因为我们什么都没做?

写一段代码试试

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs"  #>
namespace TextCode
{
    public class TestClass
    { 

    }
}

保存看看,是不是生成了代码,对,只是拷贝了一份,并没有什么魔法

再修改一下代码Entity.tt

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs"  #>
namespace TextCode
{
    public class TestClass
    {       
<#for(int i=0;i<10;i++){#>
        public string Field<#=i+1#> {get;set;}
<#}#>
    }
}

再看一下生成的代码 Entity.cs

namespace TextCode
{
    public class TestClass
    {       
        public string Field1 {get;set;}
        public string Field2 {get;set;}
        public string Field3 {get;set;}
        public string Field4 {get;set;}
        public string Field5 {get;set;}
        public string Field6 {get;set;}
        public string Field7 {get;set;}
        public string Field8 {get;set;}
        public string Field9 {get;set;}
        public string Field10 {get;set;}
    }
}

再往上看看代码,我们可以看出

  • 如果要文本输出,只要写在<##>以外就可以,反之,如果要添加模板文件要运行的代码,则需要写到<#...#>中间
  • 如果是简单的值输出,只需要写<#={运算式}#>,注意"="是必须的

好了,先开个头,你有兴趣试试吗?

相关文章

网友评论

      本文标题:自己动手做个代码生成器(一)

      本文链接:https://www.haomeiwen.com/subject/ixeafqtx.html