C# string Words to rigid the righteousness guidelines
In C#, the string word is represented by dual quotes. These literal quantities can use the rigid sequence (for example, T represents the formula, n represents the change symbol) to indicate special characters.
Convert the ordinary string to its righteous string representing form, you can consider the following methods:
Use code to generate
Using code generation technology, you can use CodedomProvider to generate the required string of string:
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();
}
}
}
Copy after login
This method follows the following steps to create a facade string representation form:
Create a stringwriter to capture generated code. -
Use CodedomProvider to generate code from the original expression of the input string. -
Extracted the generated code from StringWriter. -
Using Roslyn's Symboldisplay
A update method is to use Roslyn's microsoft.codeanalysis.csharp Nuget package:
private static string ToLiteral(string valueTextForCompiler)
{
return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);
}
Copy after login
This method generates the procedure by using Roslyn's Symboldisplay to generate the string of the righteousness, simplifying the process.
The above is the detailed content of How to Escape Strings for C# String Literals?. For more information, please follow other related articles on the PHP Chinese website!