使用T4反射获取程序集

18
我想获取特定程序集中的所有类,这是我的代码:
 var assembly=Assembly.GetExecutingAssembly();

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

当使用C#编写代码时,一切都很顺利,我也得到了我的程序集。但是,当我在t4文件中编写代码时,虽然没有出现任何错误,但我的程序集数量却不对。

1个回答

36

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

要访问你的程序集中的类型,你需要执行以下步骤:

  1. Add a reference to your assembly to the template. Put that at the top of it:

    <#@ assembly name="$(SolutionDir)<Project>\bin\Debug\<Project>.dll" #>
    
  2. Import the namespace of your assembly. Put that somewhere below the previous line:

    <#@ import namespace="<Project>.<Namespace>" #>
    
  3. To access the types in this assembly, pick one of them and get the assembly from it:

    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();
    

1
什么是汇编语言中的<Type>? - user1968030
@ShahroozJefri:在程序集中,您可以获取要获取所有类型的任何类型。例如,它可以是 RepoLib.Rts.Web.Plugins.Profiler.Models 命名空间中的某个类型。 - Daniel Hilgarth
10
如果你没有使用预处理模板,并且想要获取与T4模板所在项目中相同的类型和类的信息,我建议不要使用反射。T4模板是在设计时进行转换的,因此$(SoutionDir)<Project>\bin\Debug<Project>.dll引用的程序集可能来自于你上一次构建而且已经过时了!你可能需要使用Visual Studio代码模型(参见这里:https://dev59.com/qWYq5IYBdhLWcg3w30Tc#14402269)。 - Nico
1
你如何在不使用 type of 的情况下完成这个任务? - johnny 5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接