简体   繁体   English

T4 模板中的继承

[英]Inheritance in T4 templates

I'm trying to create a base class for all my .tt files so that I don't have to duplicate my code, but I can't figure out how to get it to work properly.我正在尝试为我的所有 .tt 文件创建一个基类,这样我就不必复制我的代码,但我不知道如何让它正常工作。

As far as I know, inheritance in .tt files must be done from precompiled code, so I have created another project so it gets compiled before my tt project does.据我所知,.tt 文件中的继承必须从预编译代码中完成,所以我创建了另一个项目,以便在我的 tt 项目之前编译它。 I have tried so many things with no result.我尝试了很多事情都没有结果。

This is my base class BaseClass.cs :这是我的基类BaseClass.cs

public class BaseClass
{
    public virtual void SaveFiles(string[] filePaths)
    {
        //Do something
    }
}

And this might be one of the classes I want to inherit from BaseClass :这可能是我想从BaseClass继承的类之一:

<#@ include file="IdentificableDomainEntityTemplate.tt" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ template language="C#" inherits="BaseClass" #>

<#+
public class IdentificableDomainEntitiesGenerator : BaseClass
{
   public string AssemblyFile {get; set;}
   public string AgentNamespace {get; set;}
   public string Namespace {get; set;}
   public string EntityName {get; set;}
   public List<string> EntitiesToGenerate;
   public List<string> ReferencesToGenerate;
   public Dictionary<string, List<string>> EntityExceptionsProperties;
   public string OutputFolder{get;set;}
   public string AddToProject{get;set;}  

   public void RunCore()
   {
    this.SaveFiles(null);       
   }
}#>

Like I said, I've created another project so it gets compiled but I don't really know what else to try in order to inherit from BaseClass in my .tt files.就像我说的,我已经创建了另一个项目,所以它被编译,但我真的不知道还有什么可以尝试从我的 .tt 文件中的BaseClass继承。

You need to include a reference to the assembly containing the BaseClass class in the T4 template as follows:您需要在 T4 模板中包含对包含BaseClass类的程序集的引用,如下所示:

<#@ assembly name="AssemblyName.dll" #>

where "AssemblyName.dll" is the name of the assembly containing the BaseClass class.其中“AssemblyName.dll”是包含BaseClass类的程序集的名称。 You will need to either provide the full path to the DLL, or you can use Visual Studio macros such as $(ProjectDir) .您需要提供 DLL 的完整路径,或者您可以使用 Visual Studio 宏,例如$(ProjectDir)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM