Work-around for C# CodeDom causing stack-overflow (CS1647) in csc.exe?

前端 未结 5 2085
滥情空心
滥情空心 2021-01-12 14:20

I\'ve got a situation where I need to generate a class with a large string const. Code outside of my control causes my generated CodeDom tree to be emitted to C# source and

5条回答
  •  鱼传尺愫
    2021-01-12 15:24

    Using a CodeSnippetExpression and a manually quoted string, I was able to emit the source that I would have liked to have seen from Microsoft.CSharp.CSharpCodeGenerator.

    So to answer the question above, replace this line:

    field.InitExpression = new CodePrimitiveExpression(HugeString);
    

    with this:

    field.InitExpression = new CodeSnippetExpression(QuoteSnippetStringCStyle(HugeString));
    

    And finally modify the private string quoting Microsoft.CSharp.CSharpCodeGenerator.QuoteSnippetStringCStyle method to not wrap after 80 chars:

    private static string QuoteSnippetStringCStyle(string value)
    {
        // CS1647: An expression is too long or complex to compile near '...'
        // happens if number of line wraps is too many (335440 is max for x64, 926240 is max for x86)
    
        // CS1034: Compiler limit exceeded: Line cannot exceed 16777214 characters
        // theoretically every character could be escaped unicode (6 chars), plus quotes, etc.
    
        const int LineWrapWidth = (16777214/6) - 4;
        StringBuilder b = new StringBuilder(value.Length+5);
    
        b.Append("\r\n\"");
        for (int i=0; i 0) && ((i % LineWrapWidth) == 0))
            {
                if ((Char.IsHighSurrogate(value[i]) && (i < (value.Length - 1))) && Char.IsLowSurrogate(value[i + 1]))
                {
                    b.Append(value[++i]);
                }
                b.Append("\"+\r\n");
                b.Append('"');
            }
        }
        b.Append("\"");
        return b.ToString();
    }
    

提交回复
热议问题