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

前端 未结 5 2241
滥情空心
滥情空心 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:08

    So am I right in saying you've got the C# source file with something like:

    public const HugeString = "xxxxxxxxxxxx...." +
        "yyyyy....." +
        "zzzzz.....";
    

    and you then try to compile it?

    If so, I would try to edit the text file (in code, of course) before compiling. That should be relatively straightforward to do, as presumably they'll follow a rigidly-defined pattern (compared with human-generated source code). Convert it to have a single massive line for each constant. Let me know if you'd like some sample code to try this.

    By the way, your repro succeeds with no errors on my box - which version of the framework are you using? (My box has the beta of 4.0 on, which may affect things.)

    EDIT: How about changing it to not be a string constant? You'd need to break it up yourself, and emit it as a public static readonly field like this:

    public static readonly HugeString = "xxxxxxxxxxxxxxxx" + string.Empty +
        "yyyyyyyyyyyyyyyyyyy" + string.Empty +
        "zzzzzzzzzzzzzzzzzzz";
    

    Crucially, string.Empty is a public static readonly field, not a constant. That means the C# compiler will just emit a call to string.Concat which may well be okay. It'll only happen once at execution time of course - slower than doing it at compile-time, but it may be an easier workaround than anything else.

提交回复
热议问题