代码之家  ›  专栏  ›  技术社区  ›  Paolo Tedesco

T4代码生成:当前项目中的访问类型

  •  17
  • Paolo Tedesco  · 技术社区  · 16 年前

    使用T4代码生成,是否可以访问当前项目中定义的类型?

    例如,如果我有一个接口,我想把它的实现委托给另一个类,即。

    interface IDoSomething {
        public void do_something();
    }
    
    class DoSomethingImpl : IDoSomething {
        public void do_something() {
            // implementation...
        }
    }
    
    class SomeClass : IDoSomething {
        IDoSomething m_doSomething = new DoSomethingImpl();
    
        // forward calls to impl object
        public void do_something() {
            m_doSomething.do_something();
        }
    }
    

    我想自动化的呼叫转移 SomeClass 使用代码生成;这可能吗?

    1 回复  |  直到 16 年前
        1
  •  1
  •   Rob    14 年前

    虽然这并不能解决锁定问题(尽管我听说VS2010可以),但您可以尝试将dll复制到一个临时位置,然后只使用复制的程序集。。

    <#@ template debug="false" hostspecific="false" language="C#" #>
    <#@ output extension=".txt" #>
    <#@ import namespace="System.Reflection" #>
    <#@ import namespace="System.IO" #>
    <#    
    var newFileName = System.IO.Path.GetTempFileName();
    System.IO.File.Copy(@"C:\Development\CustomAssembly.dll",newFileName,true);
    
    var assembly = Assembly.LoadFrom(newFileName);
    var type = assembly.GetType("CustomAssembly.DummyClass");   
    #>
    <#=newFileName#>
    <#=type#>