@Hallgrim 找到了here的CodeDom方法:
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重制。还是我们应该手动替换符号?
答案 0 :(得分:2)
您可以从输入字符串创建SyntaxNode
(LiteralExpressionSyntax
),然后采用创建的节点的字符串表示形式:
public static string ToLiteral(this string input)
{
return SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(input)).ToFullString();
}