用T4反射获得装配

17 c# reflection t4

我希望得到特定程序集中的所有类,这是我的代码

 var assembly=Assembly.GetExecutingAssembly();

 var assemblies = assembly.GetTypes().Where(t => String.Equals(t.Namespace, "RepoLib.Rts.Web.Plugins.Profiler.Models", StringComparison.Ordinal)).ToArray();
Run Code Online (Sandbox Code Playgroud)

当c#代码所有东西都没问题我得到我的程序集但是当写入t4文件我没有任何错误但我的程序集计数是.

Dan*_*rth 33

在T4模板中,执行程序集不是你的,而是来自T4引擎的程序集.

要从程序集中访问类型,必须执行以下步骤:

  1. 将程序集的引用添加到模板.把它放在它的顶部:

    <#@ assembly name="$(SolutionDir)<Project>\bin\Debug\<Project>.dll" #>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 导入程序集的命名空间.把它放在上一行的下方:

    <#@ import namespace="<Project>.<Namespace>" #>
    
    Run Code Online (Sandbox Code Playgroud)
  3. 要访问此程序集中的类型,请选择其中一个并从中获取程序集:

    var assembly = typeof(<Type in assembly>).Assembly;
    var types = assembly.GetTypes()
                        .Where(t => String.Equals(
                            t.Namespace,
                            "RepoLib.Rts.Web.Plugins.Profiler.Models",
                            StringComparison.Ordinal))
                        .ToArray();
    
    Run Code Online (Sandbox Code Playgroud)

  • 如果您没有使用预处理模板,并且希望获得有关T4模板所在的同一项目中的类型和类的信息,我建议不要使用Reflection.T4模板在设计时被转换,因此$(SoutionDir)<Project>\bin\Debug\<Project> .dll引用的程序集可能来自您的上一次构建并且已过时!您可能希望使用Visual Studio代码模型(请参阅此处:http://stackoverflow.com/questions/14134016/design-time-reflection/14402269#14402269) (9认同)