如何防止CodeMemberField插入新行?

时间:2015-04-09 17:19:16

标签: c# codedom

我使用CodeDom生成结构

var type = new CodeTypeDeclaration();
type.Name = "MyStructure";
type.IsStruct = true;
type.TypeAttributes = TypeAttributes.Public;
type.Members.

type.Members.Add(new CodeMemberField{
    Attributes = System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.Const,
    Name = "CreatedBy",
    Type = new CodeTypeReference(typeof (String)),
    InitExpression = new CodePrimitiveExpression("createdby"), 
});

type.Members.Add(new CodeMemberField{
    Attributes = System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.Const,
    Name = "ModifiedBy",
    Type = new CodeTypeReference(typeof (String)),
    InitExpression = new CodePrimitiveExpression("modifiedby")
});

当它生成时它看起来像这样:

public struct MyStructure
{

  public const string CreatedBy = "createdby";

  public const string ModifiedBy = "modifiedby";
}

但是我更喜欢它没有新的内容:

public struct MyStructure
{
   public const string CreatedBy = "createdby";  
   public const string ModifiedBy = "modifiedby";
}

是否有可能让这一代不包括新行?

2 个答案:

答案 0 :(得分:0)

发现CodeGeneratorOptions允许您指定NoLineBreaksBetweenMembers。我不想将它应用于所有内容,但我可以只创建我的结构,然后将其添加为CodeSnippetTypeMember:

type.Members.Insert(0, GenerateTypeWithoutEmptyLines(@struct));

...

/// <summary>
/// Removes the blank lines spaces by generating the code as a string without BlankLinesBetweenMembers
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private static CodeSnippetTypeMember GenerateTypeWithoutEmptyLines(CodeTypeDeclaration type)
{
    var provider = CodeDomProvider.CreateProvider("CSharp");
    using (var sourceWriter = new StringWriter())
    using (var tabbedWriter = new IndentedTextWriter(sourceWriter, "\t"))
    {
        tabbedWriter.Indent = 2;
        provider.GenerateCodeFromType(type, tabbedWriter, new CodeGeneratorOptions()
        {
            BracingStyle = "C",
            IndentString = "\t",
            BlankLinesBetweenMembers = false
        });
        return new CodeSnippetTypeMember("\t\t" + sourceWriter);
    }
}

答案 1 :(得分:0)

还有一个很好的nuget包用于C#代码生成。也许它符合您的要求。这只是一个想法,因为在我看来,删除编码对象的结果字符串中的空行是一个黑客。

http://www.codeproject.com/Articles/892114/WuffProjects-CodeGeneration