Se stai solo cercando di fare "semplice" fuga personaggi come definito sulla Microsoft site, è possibile utilizzare questa routine e salvare importazione librerie esterne:
public static class StringExtensions
{
/* https://msdn.microsoft.com/en-us/library/aa691087(v=vs.71).aspx */
private readonly static SortedDictionary<char, char> EscapeMap = new SortedDictionary<char, char>
{
{ '\'', '\'' },
{ '"', '\"' },
{ '\\', '\\' },
{ '0', '\0' },
{ 'a', '\a' },
{ 'b', '\b' },
{ 'f', '\f' },
{ 'n', '\n' },
{ 'r', '\r' },
{ 't', '\t' },
{ 'v', '\v' },
};
public static string UnescapeSimple(this string escaped)
{
if (escaped == null)
return escaped;
var sb = new StringBuilder();
bool inEscape = false;
var s = 0;
for (var i = 0; i < escaped.Length; i++)
{
if (!inEscape && escaped[i] == '\\')
{
inEscape = true;
continue;
}
if (inEscape)
{
char mapChar;
if (EscapeMap.TryGetValue(escaped[i], out mapChar))
{
sb.Append(escaped.Substring(s, i - s - 1));
sb.Append(mapChar);
s = i + 1;
}
inEscape = false;
}
}
sb.Append(escaped.Substring(s));
return sb.ToString();
}
}
Ecco uno unit test per dimostrarlo:
[TestMethod]
public void UnescapeSimpleTest()
{
var noEscapes = @"This is a test".UnescapeSimple();
Assert.AreEqual("This is a test", noEscapes, nameof(noEscapes));
var singleEscape = @"\n".UnescapeSimple();
Assert.AreEqual("\n", singleEscape, nameof(singleEscape));
var allEscape = @"\'\""\\\0\a\b\f\n\r\t\v".UnescapeSimple();
Assert.AreEqual("\'\"\\\0\a\b\f\n\r\t\v", allEscape, nameof(allEscape));
var textInEscapes = @"\tthis\n\ris\\a\ntest".UnescapeSimple();
Assert.AreEqual("\tthis\n\ris\\a\ntest", textInEscapes, nameof(textInEscapes));
var backslashNoEscapes = @"\,\h\qtest".UnescapeSimple();
Assert.AreEqual(@"\,\h\qtest", backslashNoEscapes, nameof(backslashNoEscapes));
var emptyStr = "".UnescapeSimple();
Assert.AreEqual("", emptyStr, nameof(emptyStr));
// Prove Enviroment.NewLine is "\r\n" and not "\n\r" (Windows PC)
var newLine = @"\r\n".UnescapeSimple();
Assert.AreEqual(Environment.NewLine, newLine, nameof(newLine));
// Double check prior test (Windows PC)
var newLineWrong = @"\n\r".UnescapeSimple();
Assert.AreNotEqual(Environment.NewLine, newLineWrong, nameof(newLineWrong));
}
Sentitevi liberi di modificare l'EscapeMap o rinominare la funzione UnescapeSimple (imbarazzante lo so).
Si noti che questa soluzione non gestisce caratteri di escape Unicode o esadecimale o ottale, semplicemente gestisce i semplici quelli singolo carattere.
Tu conosci il tuo Assert fallirà, non è vero? E il secondo metodo non usa il suo parametro. –
È un Nunit Assert, ho modificato il codice per usare un debug.assert. Il secondo metodo è uno stub TDD (Test driven design), la risposta alla domanda fornirà una soluzione più generale –
ancora presenti 2 funzioni non correlate. L'ultima riga mi ha aiutato a capire, il codice mi ha solo confuso. –