【问题标题】:Generate code through Reflection over the same assembly通过反射在同一个程序集上生成代码
【发布时间】:2013-03-25 22:38:47
【问题描述】:

我已经开始涉足 T4 并且最初相处得很好,但后来遇到了一个实际上非常明显且可能无法解决的问题,但也许有一种方法我只是缺乏了解或了解的经验。

给定以下类:

public class T4Test : CodeActivity
{
    protected override void Execute(CodeActivityContext context)
    {
    }

    [Input("InX")]
    public InArgument<string> InX { get; set; }

    [Output("OutX")]
    public OutArgument<string> OutX { get; set; }
}

我想要这个作为输出:

public class ActivityWrapper
{
    private readonly T4Test _activity;
    private readonly ActivityContext _context;

    public ActivityWrapper(T4Test activity, ActivityContext context)
    {
        this._activity = activity;
        this._context = context;
    }

    public string InX
    {
        get { return this._activity.InX.Get(this._context); }
    }

    public string OutX
    {
        get { return this._activity.OutX.Get(this._context); }
        set { this._activity.OutX.Set(this._context, value); }
    }
}

我已经弄清楚了我需要的反射材料,并且我知道 T4 代码应该是什么样子,但是有一个问题:我需要它与 T4Test 类在同一个项目中。但是,要加载程序集并对其进行反映,需要对其进行编译——但如果我打算修改同一个程序集的代码,那当然有点困难。 (而且我猜 NCrunch 并没有简化事情。)

现在,我希望仍然可以解决这个问题:

  • 项目将在没有生成的类的情况下编译。这是因为该类将实现由 IoC 容器自动注册/解析的接口。无论如何它也无法测试,因为ActivityContext 不能被嘲笑。
  • 因此,它不必一直存在或纠正。在实际交付 DLL 之前,我只需要能够说“立即生成”即可。
  • 出于同样的原因,我也不关心 T4 模板是否实际位于项目中 - 只要生成的文件最终位于项目中(尽管不需要另一个项目作为模板并构建 PostBuild 事件来复制.cs 归档)。
  • 准确地说,它甚至不需要是 T4。如果有其他可行的方法,我也很乐意使用。

有什么方法可以实现吗? (这是否足够清楚?)

【问题讨论】:

  • 你考虑过在T4模板中生成整个类吗?即定义一些辅助方法来创建一个小的 DSL,然后在模板中列出要生成的类成员?
  • 您的意思是用不同的形式(XML 左右)定义属性,然后从模板生成两个类?考虑到我正在处理的有限变化,这实际上可能有效。 “辅助方法”的背后是什么;这些是干什么用的?
  • 是的,从模板生成两个类。我将发布一个示例来说明辅助方法。
  • 一个更复杂的答案是使用 roslyn 来解析 C# 语法树,但老实说@dtb 建议更好。

标签: c# .net reflection t4


【解决方案1】:

我想提出一种替代方法来反映生成的程序集,因为转换 T4 仅在项目成功构建并在程序集没有过时时生成正确的输出时才有效。

如果您使用特定于主机的 T4 模板,您可以通过 EnvDTE 接口访问 Visual Studio 自动化模型。使用它,您可以遍历当前加载的 Visual Studio 解决方案的 CodeModel,而无需先构建它。

看看我对这个 SO 问题的回答:Design Time Reflection。借助有形模板库中的免费模板,您可以在设计时轻松地“反映”现有类并检测装饰有所需属性的属性:

<#
var project = VisualStudioHelper.CurrentProject;

// get all class items from the code model
var allClasses = VisualStudioHelper.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false);

// iterate all classes
foreach(EnvDTE.CodeClass codeClass in allClasses)
{
    // iterate all properties
    var allProperties = VisualStudioHelper.GetAllCodeElementsOfType(codeClass.Members, EnvDTE.vsCMElement.vsCMElementProperty, true);
    foreach(EnvDTE.CodeProperty property in allProperties)
    {
        // check if it is decorated with an "Input"-Attribute
        if (property.Attributes.OfType<EnvDTE.CodeAttribute>().Any(a => a.FullName == "Input"))
        {
            ...
        }
    }
}
#>

【讨论】:

  • 谢谢。这几乎就是我最初寻找的东西,但显然,鉴于我这一代输入的性质,我并没有寻找正确的东西。
【解决方案2】:

T4Test.tt

<#@ include file="Activities.tt" #>
<#
var t4test = new Activity("T4Test")
{
    Input("InX"),
    Output("OutX"),
};
GenerateCode(t4test);
#>

Activity.tt

<#@ template language="C#" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
<#+
class Activity : IEnumerable<Property>
{
    private string name, wrapper;
    private List<Property> properties;
    public Activity(string name, string wrapper = null)
    {
        this.name = name;
        this.wrapper = wrapper ?? name + "Wrapper";
        this.properties = new List<Property>();
    }
    public void Add(Property property)
    {
        this.properties.Add(property);
    }
    public IEnumerator<Property> GetEnumerator()
    {
        return this.properties.GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    public void GenerateCode()
    {
        // ...
    }
}
class Property
{
    private bool output;
    private string name, type;
    public Property(bool output, string name, string type)
    {
        this.output = output;
        this.name = name;
        this.type = type;
    }
}
Property Input(string name, string type = "string")
{
    return new Property(false, name, type);
}
Property Output(string name, string type = "string")
{
    return new Property(true, name, type);
}
void GenerateCode(params Activity[] activities)
{
    WriteLine("namespace Foo");
    WriteLine("{");
    PushIndent("   ");
    foreach (var activity in activities)
    {
        WriteLine("class " + activity.name);
        WriteLine("{");
        PushIndent("   ");
        // ...
        PopIndent();
        WriteLine("}");
    }
    PopIndent();
    WriteLine("}");
}
#>

【讨论】:

  • 谢谢;明天我必须以更好的状态来看待这个问题。我现在似乎明白的是,在日常使用中,当我将其放入项目时,这将是一个缺少第二个代码块(var t4test 等)的.tt 文件,我只需要通过添加该声明,对吗?这实际上可能比仅仅生成包装类节省更多的工作,因为活动类本身已经几乎所有样板。
  • 是的。您甚至可以将模板拆分为两个文件。我已经相应地更新了示例。
  • 谢谢;这似乎是最灵活和最有效的选择 - 但我如何实际生成代码?如何从GenerateCode() 写入输出文件?
  • 您似乎无法从嵌套类生成代码;我已经相应地更新了示例。
  • 我现在明白了; WriteLine 的东西正是我想要的。我认为它应该以这种方式工作,但不知道方法名称。东西现在开始到位。 :-)
猜你喜欢
  • 2011-02-07
  • 2014-05-19
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多