使用Roslyn将C#字符串值转换为转义的字符串文字

问题描述:

@Hallgrim 发现了这样的CodeDom方法,

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();
        }
    }
}

如今,我们需要对.NET Core进行Roslyn重制.还是我们应该手动替换符号?

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

您可以从输入字符串创建 SyntaxNode ( LiteralExpressionSyntax ),然后采用以下形式表示创建的节点:

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();
}