开发者

Prevent CodeDom from splitting large strings

开发者 https://www.devze.com 2023-02-13 15:33 出处:网络
I am using CodeDom to generate C# code, and part of that involves to spitting out String variable contents. Sometimes, these strings can get to be quite long.

I am using CodeDom to generate C# code, and part of that involves to spitting out String variable contents. Sometimes, these strings can get to be quite long.

Is there a way to prevent the CodeDom code generator from splitting those large strings into s开发者_JS百科maller chunks? What the generator does is that it splits the long strings into a few smaller ones, and inserts a concatenation operator in between. While the code compiles fine, I don't like how it messes up the readability of my code.


Hmm.. I don't think so. Poking with .NET Reflector into the source code of Microsoft.CSharp.CSharpCodeGenerator (System's internal), we find this:

private void GeneratePrimitiveExpressionBase(CodePrimitiveExpression e)
{
...
    else if (e.Value is string)
    {
        this.Output.Write(this.QuoteSnippetString((string) e.Value));
    }
...
}

and ... this:

private string QuoteSnippetString(string value)
{
    if (((value.Length >= 0x100) && (value.Length <= 0x5dc)) && (value.IndexOf('\0') == -1))
    {
        return this.QuoteSnippetStringVerbatimStyle(value);
    }
    return this.QuoteSnippetStringCStyle(value);
}

And if you dig further, both functions are not configurable.


I think I have found a way around this: In short, instead of using a CodePrimitiveExpression to output my string, I was able to use a CodeSnippetExpression by explicitly quoting my string argument to it.

CodeExpression x = new CodeSnippetExpression("\"" + myLongString + "\"");

Works for the few cases where I've had to use it, but of course I haven't tested all scenarios.

0

精彩评论

暂无评论...
验证码 换一张
取 消