我一直在使用 CodeDom 进行一些代码生成。它工作得很好,但我还没有找到将生成的源代码文件包含在项目中的方法。我开始使用 T4 和T4Toolbox来生成代码,因为它支持与项目文件的集成。
有谁知道 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 的东西只是在磁盘上输出文件而不更新项目文件。
这是一个视觉效果: