使用.NET CodeDom代码生成时,如何自定义自动生成的注释?

我正在使用CodeCompileUnitCSharpCodeProvider来生成一些源代码。 它将下面的标题添加到所有生成的代码中。 有没有办法自定义评论,所以它说了别的什么?

 //  // This code was generated by a tool. // Runtime Version:2.0.50727.3053 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. //  

你不能。 我建议在此之后立即添加您自己的评论。 以下是如何执行此操作的示例: http : //www.codeproject.com/KB/dotnet/ResourceClassGenerator.aspx

您只需在文件开头添加注释,如下所示:

 //---------------------------------------------------------------------------- // My comments // Are go here //---------------------------------------------------------------------------- //  // This code was generated by a tool. // Runtime Version:2.0.50727.3053 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. //  //---------------------------------------------------------------------------- 

就在将CompileUnit生成到TextWriter之前,请执行以下操作:

 CSharpCodeProvider provider = new CSharpCodeProvider(); var tw = new IndentedTextWriter(new StreamWriter(filename, false), " "); tw.WriteLine("//----------------------------------------------------------------------------"); tw.WriteLine("// My comments"); tw.WriteLine("// Are go here"); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); 

由于你无法通过CodeDom中提供的API来实现,所以这里有一些代码我刚刚为自己解决了这个问题。 不完美,但诀窍。

 var marker = "//------------------------------------------------------------------------------"; var allTheCode = sw.ToString(); var justTheRealCode = allTheCode.Substring(allTheCode.IndexOf(marker) + marker.Length, allTheCode.LastIndexOf(marker) + marker.Length); justTheRealCode = allTheCode.Substring(justTheRealCode.Length); 

非常kludgy,但是当我需要这样做的时候,我创建了一个包装输出流并从前十行中删除的类:

  ///  /// Removes the first 10 lines from the output. This removes the junk from the .NET Code Generator. ///  internal class CodeOutputHelper : TextWriter { private readonly TextWriter _Inner; private int _CountDown = 10; public CodeOutputHelper( TextWriter inner ) { _Inner = inner; } public override void WriteLine(string s) { if( _CountDown-- <= 0 ) { _Inner.WriteLine(s); } } public override void Write( string value ) { if (_CountDown<=0) _Inner.Write( value ); } public override void Write( char value ) { _Inner.Write( value ); } public override Encoding Encoding { get { return _Inner.Encoding; } } } } 

虽然CodeDOM似乎没有直接支持这一点,但您可以使用这个注释由标记明确分隔的事实。 因此,您只需在CodeDOM的输出上执行字符串操作即可更改此注释:

 var provider = new CSharpCodeProvider(); string generatedCode; using (var output = new StringWriter()) { provider.GenerateCodeFrom…(…, output, …); generatedCode = output.ToString(); } string modifiedCode = Regex.Replace(generatedCode, …); // modify the output as you see fit