CodeDom を使用してコード生成を行っています。うまく機能しますが、生成されたソース コード ファイルをプロジェクトに含める方法が見つかりませんでした。プロジェクト ファイルとの統合をサポートしているため、T4 とT4Toolboxを使用してコードを生成するようになりました。
CodeDom もこの機能をサポートしているかどうかは誰にもわかりませんか? この 1 つの機能しかサポートしていない場合は、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 で使用するコードの 2 番目の例を次に示します。これは、テンプレートが変換されるプロジェクトの一部として出力を指定します。
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 コードはファイルをプロジェクトの "Domain" フォルダーに出力します。しかし、CodeGen のものはディスク上のファイルを出力するだけで、プロジェクト ファイルを更新しません。
ここにビジュアルがあります: