T4模板使用笔记
路径获取
① 获取当前解决方案路径
string solutionsPath = Host.ResolveAssemblyReference("$(SolutionDir)");
② 获取当前项目路径
string projectPath = Host.ResolveAssemblyReference("$(ProjectDir)");
一个简单的Demo
<#@ template debug="false" hostspecific="true" language="C#" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.IO" #> <#@ import namespace="System.Reflection" #> <#@ assembly name="$(SolutionDir)\TestT4.Core\bin\Debug\TestT4.Core.dll" #> <#@ import namespace="TestT4.Core" #> <# string solutionsPath = Host.ResolveAssemblyReference("$(SolutionDir)"); string projectPath = Host.ResolveAssemblyReference("$(ProjectDir)"); #> <# AppDomainTypeFinder appDomainTypeFinder=new AppDomainTypeFinder(); var assemblies = appDomainTypeFinder.GetAssemblies(); IEnumerable<Type> types = new List<Type>(); foreach (var assemblie in assemblies) { types = types.Concat(assemblie.GetTypes(). Where(type => !String.IsNullOrEmpty(type.Namespace)). Where(type => type.BaseType != null &&type.BaseType == typeof(BaseEntity))); } foreach (var type in types) { var typenamespace = type.Namespace; if (!string.IsNullOrEmpty(typenamespace)) { var splitNamespace = typenamespace.Split('.'); if(splitNamespace.Length>0){ var fileFolder=projectPath+@"\"+splitNamespace[splitNamespace.Length-1]; if(!Directory.Exists(fileFolder)) { Directory.CreateDirectory(fileFolder); } string contractFileName= type.Name+"Map.cs"; string filePath = Path.Combine(fileFolder,contractFileName); File.Delete(filePath); File.AppendAllText(filePath,type.Name+"123"); } } } #>