C# 通过T4自动生成代码
通过T4模板生成代码,运行时实现
关键代码段:Host
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) == )
{
//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
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);
}
}
}
入口
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 = "" };
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文件
<#@ 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 #>
<# } #>
自定义参数
[Serializable]
public class testType
{
public string Name { get; set; }
}
C# 通过T4自动生成代码的更多相关文章
- mybatis generator maven插件自动生成代码
如果你正为无聊Dao代码的编写感到苦恼,如果你正为怕一个单词拼错导致Dao操作失败而感到苦恼,那么就可以考虑一些Mybatis generator这个差价,它会帮我们自动生成代码,类似于Hiberna ...
- java如何在eclipse编译时自动生成代码
用eclipse写java代码,自动编译时,如何能够触发一个动作,这个动作是生成本项目的代码,并且编译完成后,自动生成的代码也编译好了, java编辑器中就可以做到对新生成的代码的自动提示? 不生成代 ...
- MyBatis自动生成代码示例
在项目中使用到mybatis时,都会选择自动生成实体类,Mapper,SqlMap这三个东东. 手头上在用的又不方便,找了下网上,其实有很多文章,但有些引用外部文件时不成功,也不方便,所以重新整理了下 ...
- MyBatis使用Generator自动生成代码
MyBatis中,可以使用Generator自动生成代码,包括DAO层. MODEL层 .MAPPING SQL映射文件. 第一步: 配置好自动生成代码所需的XML配置文件,例如(generator. ...
- mybatis 自动生成代码(mybatis generator)
pom.xml 文件配置 引入 mybatis generator <properties> <mysql.connector.version>5.1.44</mysql ...
- ButterKnife的使用以及不能自动生成代码问题的解决
ButterKnife的使用以及不能自动生成代码问题的解决 转载请注明出处:http://www.cnblogs.com/zhengjunfei/p/5910497.html 最近换了个工作刚入职,又 ...
- 【MyBatis】MyBatis自动生成代码查询之爬坑记
前言 项目使用SSM框架搭建Web后台服务,前台后使用restful api,后台使用MyBatisGenerator自动生成代码,在前台使用关键字进行查询时,遇到了一些很宝贵的坑,现记录如下.为展示 ...
- mybatis-generator : 自动生成代码
[参考文章]:mybatis generator自动生成代码时 只生成了insert 而没有其他 [参考文章]:Mybatis Generator最完整配置详解 1. pom <plugin&g ...
- mybatis-generator自动生成代码插件
mybatis自动生成代码(实体类.Dao接口等)是很成熟的了,就是使用mybatis-generator插件. 它是一个开源的插件,使用maven构建最好,可以很方便的执行 插件官方简介: http ...
随机推荐
- idea 下maven 导入本地jar,以及导入之后 java不能引用问题
1.在当前的项目中新建立一个lib文件夹,将需要导入的jar放入其中. 2.配置pom.xml 文件 <!--导入本地jar--> <dependency> <group ...
- RHEL5.8上SAMBA源码修改打包安装流程
之前一直使用系统自带的SAMBA,近期需要对SAMBA代码做一些修改,然后还是打算用RPM包的方式来安装部署. 这个流程本身不复杂,在这里记录下来,免得在另外写说明文档. 关键词:RHEL5.8, s ...
- 洛谷P1724 东风谷早苗
题目描述 在幻想乡,东风谷早苗是以高达控闻名的高中生宅巫女.某一天,早苗终于入手了最新款的钢达姆模型.作为最新的钢达姆,当然有了与以往不同的功能了,那就是它能够自动行走,厉害吧(好吧,我自重).早苗的 ...
- 朴素贝叶斯法(naive Bayes)
<统计学习方法>(第二版)第4章 4 朴素贝叶斯法 生成模型 4.1 学习与分类 基于特征条件独立假设学习输入输出的联合概率分布 基于联合概率分布,利用贝叶斯定理求出后验概率最大的输出 条 ...
- postman对登陆进行压力测试的方法
1.填写完整参数,设置好变量,选择好环境,保存好 2.将变量mobile_phone和password的值以如下图的格式,填写到Excel表格中,然后以csv(逗号分隔)的形式进行保存 3.点击此测试 ...
- cocos2dx 接入bugly 报错 Fail to get class by NSClassFromString(BuglyAgent)
ios 端安装文档接入库后,报错 -> static void BuglyJSAgent::reportJSError(JSContext *, const char *, JSErrorRep ...
- 数据库sql语句limit区别
注意:并非所有的数据库系统都支持 SELECT TOP 语句. MySQL 支持 LIMIT 语句来选取指定的条数数据, Oracle 可以使用 ROWNUM 来选取. SQL Server / MS ...
- faster rcnn环境编译
步骤和fast rcnn的编译一样,在编译中遇到了一个问题: 刚开始是以为python-numpy没有安装到位,后来发现是Makefile.config的配置出现了问题.原来的配置是: PYTHON_ ...
- 关于Error:Maven Resources Compiler: Maven project configuration required for module '项目名' isn't available. Compilation of Maven projects is supported only&
总是出现Error:Maven Resources Compiler: Maven project configuration required for module '项目名' isn't avai ...
- 牛客网练习赛25 C 再编号
链接:https://www.nowcoder.com/acm/contest/158/C来源:牛客网 定义对 a 的再编号为 a' ,满足 . 现在有 m 次询问,每次给定 x,t ,表示询问经过 ...