且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关于 T4 模板的学术查询

更新时间:2023-12-02 21:13:28

我试图实现类似的目标,并且效果很好.在下面的示例 .tt 文件中,我所指的同一解决方案中我自己的程序集的名称是 SomeLibrary.我正在思考的类是一个名为 SomeLibrary.SomeInterface 的接口.有很多方法可以使这更通用,但我不想让示例太复杂.另外,请不要关注这个模板的整体结果,这只是为了让您对它的工作方式有一个印象:

I was trying to achieve something similar and it works fine. In the example .tt file below, the name of my own assembly in the same solution that I am referring to is SomeLibrary. The class I am reflecting on is an interface called SomeLibrary.SomeInterface. There are ways to make this more generic, but I did not want to make the sample too complicated. Also, please do not pay attention to the overall result of this template, this is just to give you an impression on how it would work:

<#@ template language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="$(SolutionDir)$(SolutionName)\bin\$(ConfigurationName)\$(SolutionName).dll" #>
<#@ import namespace="System.Reflection" #>
<#
    Type someIType = typeof(SomeLibrary.SomeInterface);
#>
namespace SomeLibrary
{
    class <#=someIType.Name#>Impl: <#=someIType.Name#>
    {
        <#=someIType.Name#> encapsulatedIntf;
        public <#=someIType.Name#>Impl(<#=someIType.Name#> anIntf)
        {
            encapsulatedIntf = anIntf;
        }

        // Methods to be implemented:
<#
    MethodInfo[] methods = someIType.GetMethods();
    foreach (MethodInfo m in methods)
    {
#>
        // <#=m#>;
<#
    }
#>
    }
}

就我而言,这会导致

namespace SomeLibrary
{
    class SomeInterfaceImpl: SomeInterface
    {
        SomeInterface encapsulatedIntf;
        public SomeInterfaceImpl(SomeInterface anIntf)
        {
            encapsulatedIntf = anIntf;
        }

        // Methods to be implemented:
        // Int32 someMethod(Int32);
        // System.String someOtherMethod();
    }
}