我一直在使用CodeDom来做一些代码生成。它工作的很好,但我还没有找到一种方法将生成的源代码文件包含在项目中。我开始使用T4和T4Toolbox来生成代码,因为它支持与项目文件的集成。CodeDom可以将源代码文件添加到项目中吗?
有谁知道CodeDom是否也支持这个功能?如果仅支持这一功能,我会考虑再次查看CodeDom。
下面是如何使一个源代码文件,CodeDom中的例子:
protected void CreateSourceFile(CodeCompileUnit codeCompileUnit,
string fileName,
out string fileNameWithExtension)
{
fileNameWithExtension = string.Format("{0}.{1}",
fileName,
CodeProvider.FileExtension);
var indentedTextWriter =
new IndentedTextWriter(new StreamWriter(fileNameWithExtension,
false),
TabString);
CodeProvider.GenerateCodeFromCompileUnit(codeCompileUnit,
indentedTextWriter,
new CodeGeneratorOptions());
indentedTextWriter.Close();
}
这工作正常,但它只是输出文件到硬盘中的某个地方(可能bin文件夹)。
下面是一些代码,我用T4使用第二个例子中,这个规定作为项目的一部分模板变换输出:
public class RDFSClassGenerator : Generator
{
private readonly string rootNamespace;
private readonly string ontologyLocation;
public RDFSClassGenerator(
string rootNamespace,
string ontologyLocation)
{
this.rootNamespace = rootNamespace;
this.ontologyLocation = ontologyLocation;
}
protected override void RunCore()
{
XElement ontology = XElement.Load(ontologyLocation);
var service = new RDFSGeneratorService(ontology);
foreach (MetaClass metaClass in service.MetaClasses)
{
var rdfsClassTemplate = new RDFSClassTemplate(rootNamespace, metaClass);
rdfsClassTemplate.Output.File = "Domain/" + metaClass.Name + ".cs";
rdfsClassTemplate.Render();
}
}
}
所以T4代码将输出文件导入我的项目的“域”文件夹。但CodeGen的东西只是在磁盘上输出文件,并没有更新项目文件。
这里是一个可视化:
嗯,不知道你在做什么。你正在将CodeDom与t4混合?我使用T4将模板添加到解决方案中,然后使用EnvDTE将文件添加到解决方案中。也许你需要澄清你在做什么? – Will 2010-07-28 12:11:02
@我刚刚在CodeDom和T4的不同方式上面添加了一些示例。这听起来像我可能需要看看EnvDTE? – 2010-07-28 12:32:33