Why is my Dictionary adding extra escape character

2019-07-18 16:34发布

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="1" value="An error occured.\r\nPlease try again later." />
  </appSettings>
</configuration>

Code:

Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
string key = "1";

keyValuePairs.Add(key, ConfigurationManager.AppSettings["key"]);

if (keyValuePairs.ContainsKey(key))
{
  // when I hover over the object, keyValuePairs, in my debugger, I see, "An error occured.\r\nPlease try again later."
  string value1 = keyValuePairs[key];
  // now when I hover over the local variable, value, I see, "An error occured.\\r\\nPlease try again later."
}

I'm curious as to why the above code adds escape characters to "\r\n" to make it "\r\n"

I'd also like to know how to avoid getting the extra "\" characters.

2条回答
Juvenile、少年°
2楼-- · 2019-07-18 17:22

The dictionary isn't doing anything to your string. The debugger, or more specifically the expression evaluator, will alter the format of a displayed string when it contains newline characters. The end goal is to make it display better on the single line the debugger typically has for values.

I recently did a blog post which goes into detail about what the debugger does and the reason behind the design

EDIT

I believe there is a bug in your sample code. I think you left at @ symbol off of the value in the add of the Dictionary. Without the @ symbol I do not get your repro but with it I do. Assuming the @ is missing though ...

The reason why you see the string with extra escapes is that the debugger always displays strings as string literals and not verbatim strings. In a string literal you need the double escape to match the equivalent code in the verbatim string. Hence \n becomes \\n

查看更多
何必那么认真
3楼-- · 2019-07-18 17:34

If you are reading the string from the app.config, I assume it's something like the following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="errorString" value="An error occured.\r\nPlease try again later."/>
  </appSettings>
</configuration>

In which case your sample code should look like this:

keyValuePairs.Add("1", @"An error occured.\r\nPlease try again later.");

And from there it should be obvious why the debugger is displaying as it does (especially if you read JaredPar's answer.

You're better off using a resource dictionary for storing the string, which will easily let you insert newline characters in the VS editor.

Edit: Just on a whim, I tried the following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="errorString" value="An error occured.
Please try again later."/>
  </appSettings>
</configuration>

Compiled fine and produced the correct results.

查看更多
登录 后发表回答