簡體   English   中英

T4模板實現接口

[英]T4 template to implement interface

我正在閱讀有關T4模板的資料。 我想知道是否有可能我們從.cs文件(接口)讀取並使用T4模板生成界面實現?

我已經看到了一些示例,但與從.cs文件讀取並使用.tt生成另一個.cs文件無關

如果沒有接口DLL,則可以在T4生成期間直接編譯.cs代碼,並在生成的程序集中使用反射來解析生成實現的方法。

<#@ assembly name="System.Core" #>
<#@ import namespace="System.CodeDom.Compiler" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="Microsoft.CSharp" #>
<#+
public class ImplementationGenerator
{
   private Assembly interfaceAssembly;

   public ImplementationGenerator(string interfaceCsFileName, string[] additionalAssemblyNames = null)
   {
       List<string> assemblyNames = new List<string>(new string[] { "System.dll", "System.Core.dll" });
       if (null != additionalAssemblyNames)
       {
           assemblyNames.AddRange(additionalAssemblyNames);
       }
       CompilerParameters parameters = new CompilerParameters(assemblyNames.ToArray())
       {
           GenerateExecutable = false,
           IncludeDebugInformation = false,
           GenerateInMemory = true
       };
       CSharpCodeProvider csProvider = new CSharpCodeProvider();
       CompilerResults interfaceResults = csProvider.CompileAssemblyFromFile(parameters, interfaceCsFileName);
       if (interfaceResults.Errors.HasErrors)
       {
           string errorMessage = "The compiler returned the following errors:\n";
           foreach (CompilerError error in interfaceResults.Errors)
           {
               errorMessage += "\t"+error.ErrorText+"\n";
           }
           throw new Exception(errorMessage);
       }
       interfaceAssembly = interfaceResults.CompiledAssembly;
   }

   public void Generate()
   {
       //use reflection to parse interfaceAssembly methods and generate the implementation
   }
}

做這件事有很多種方法:

  1. 通過使用匯編導入指令來引用您的dll和定義類的名稱空間。 因此,您可以使用已經編譯的.NET代碼(例如,您的項目)。 如果某些類型/成員是私有的,請向反射打招呼。 這是很酷的方法,因為您正在使用代碼,因此可以編譯(因為它已經編譯過)&&如果.cs依賴於匯編中的另一個類,則可以了解此類。

  2. 您可以使用代碼模型框架來解析* .cs。 您可以在此處看到一些示例: 用於從C#枚舉生成SQL視圖的T4模板

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM