Convert a C# string value to an escaped string literal with Roslyn

左心房为你撑大大i 提交于 2021-01-28 06:11:33

问题


There is such method for CodeDom by @Hallgrim found here:

private static string ToLiteral(string input)
{
    using (var writer = new StringWriter())
    {
        using (var provider = CodeDomProvider.CreateProvider("CSharp"))
        {
            provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
            return writer.ToString();
        }
    }
}

Nowadays we need a Roslyn remake for .NET Core. Or should we manually replace symbols?


回答1:


You can create a SyntaxNode (LiteralExpressionSyntax) from the input string and than take the string representation of the created node:

public static string ToLiteral(this string input)
{
    return SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(input)).ToFullString();
}


来源:https://stackoverflow.com/questions/55514123/convert-a-c-sharp-string-value-to-an-escaped-string-literal-with-roslyn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!