t4b代码生成_用T4模板实现简单的代码生成器

最近想在项目中使用一个代码生成器,用T4模板实现了,还是蛮方便的。关于T4模板的介绍可以看下园中相关系列文章T4的介绍,创建运行时模板。里面介绍蛮详细的。

代码生成器界面如下,比较简单,我这里是通过传入实体类名称生成对应层的代码:

添加预处理的模板 IDal.tt(其他类似),代码如下:

View Code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Model;

namespace IDal

{

public interface IDal : IRepository<>

{

}

}

同时新建一个IDal的部分类:

View Code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace CodeBuilder.Template

{

public partial class IDal

{

public string ClassNames

{

get;

set;

}

public IDal(string _ClassNames)

{

this.ClassNames = _ClassNames;

}

}

}

default.aspx.cs主要代码:

View Code

#region 通过反射取得要生成的类

Assembly ass = Assembly.Load("Template"); //获取程序集                        Type myclass = null;

MethodInfo mymethod = null;

foreach (var name in list)

{

foreach (ListItem item in chkboxType.Items)

{

if (item.Selected)

{

Type[] mytypes = ass.GetTypes();

foreach (Type t in mytypes)

{

if (t.Name == item.Text)

{

myclass = t;

break;

}

}

Object obj = Activator.CreateInstance(myclass, name);

mymethod = myclass.GetMethod("TransformText"); //取TransformText()函数                                    String pageContent = mymethod.Invoke(obj, null).ToString();

//创建文件                                    File.AppendAllText(dirpath + @"\" + string.Format(item.Value, name) + ".cs", pageContent);

}

}

}

#endregion

#region

这里通过反射查找所有要生成的模板文件并创建文件,通过myclass.GetMethod("TransformText")调用TransformText方法,取得要生成的文件中内容。

我这里生成的代码主要是为了符合自己项目的需要,实际使用中可以根据需要扩展如通过数据库表生成model,存储过程等

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值