设计时间反思 [英] Design Time Reflection

查看:83
本文介绍了设计时间反思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在设计时进行反射预编译?

Is there a way to do reflection pre-compile - at design time?

我的目的是使用T4来基于实现某些特定类的自定义代码接口。我知道我可以进行反思,但是我希望T4脚本在编译之前吐出其他代码,否则我将需要编译两次代码,一次生成dll,两次让T4反映先前生成的dll并添加

My intent is to use T4 to spit out custom codes based on classes that implement certain interfaces. I know I can call upon reflection, but I want the T4 script to spit out the additional code before compile, otherwise I will need to compile the code twice, once to generate dlls, twice to let T4 reflect on the previously generated dll and add additional scaffolding.

在设计时是否可以进行反射?

Is there a way to do reflection at design time?

是否有更好的方法可以进行反射?

Is there a better way to do this?

推荐答案

实际上有一种方法可以基于Visual Studio自动化:项目界面提供了包含图形的属性 CodeModel该项目中所有模型工件的数量。您可能需要遍历它,以便找到基于其生成输出代码的类,接口,属性...。

There actually is a way of generating code pre-build based on the CodeModel provided by Visual Studio Automation: The Project Interface provides a Property "CodeModel" that contains a graph of all model artifacts in that project. You might want to traverse it in order to find classes, interfaces, properties, ... based on which you generate your output code.

dandrejw已经提到了 Tangible T4-Editor 。它有一个免费的模板库。有一个可重用的模板有形的Visual Studio自动化帮助器,在您的情况下应该会非常有用。使用此模板,您可以解决以下问题:

dandrejw already mentioned the Tangible T4-Editor. It has got a free template gallery. There is a reusable template "tangible Visual Studio Automation Helper" which should be extremely helpful in your case. Using this template you could solve your issue like this:

这是t4模板中的代码,用于检测实现INotifyPropertyChanged的所有类。

This is code within a t4 template detecting all classes that implement INotifyPropertyChanged.

<#
    // get a reference to the project of this t4 template
    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)
    {
        // get all interfaces implemented by this class
        var allInterfaces = VisualStudioHelper.GetAllCodeElementsOfType(codeClass.ImplementedInterfaces, EnvDTE.vsCMElement.vsCMElementInterface, true);
        if (allInterfaces.OfType<EnvDTE.CodeInterface>()
                         .Any(i => i.Name == "INotifyPropertyChanged"))
        {
            #>Render your code here<#
        }
    }
#>

将您的输出代码放在代码段显示为在此处呈现代码的位置。

Put your output code where the code snippet says "Render your code here".

这篇关于设计时间反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆