在进行代码审查时,我发现一位老同事编写的代码有以下情况:
const string replacement = @"";
这个字符串被用在正则表达式中,作为匹配后替换的内容。我的问题是在一个空字符串前面添加@字面符号有什么作用。因为应该没有需要直接解释的内容。
@"";
和 "";
之间有区别吗?
这个字符串用于正则表达式
正则表达式中大量使用 \
字符。例如,以下是一个正则表达式,用于匹配从 0
到 100
的百分比,始终保留四位小数:
^(100\.0000|[1-9]?\d\.\d{4})$
由于在常见的C#语法中需要将\
转义为\\
,@""
形式使得正则表达式更容易被阅读,对比如下:
"^(100\\.0000|[1-9]?\\d\\.\\d{4})$"
@"^(100\.0000|[1-9]?\d\.\d{4})$"
@""
形式的习惯,即使在没有区别的情况下也是如此。首先,如果他们以后改用某些需要区别的东西,则只需更改表达式,而不是字符串本身的代码。@""
而不是""
的原因。.NET生成的内容相同,但他们习惯于在正则表达式中使用@""
。请查看MSDN的字符串字面量文档。对于空字符串,它没有影响,但是可以改变某些字符转义序列以及换行处理的行为。以下示例摘自MSDN网站:
string a = "hello, world"; // hello, world
string b = @"hello, world"; // hello, world
string c = "hello \t world"; // hello world
string d = @"hello \t world"; // hello \t world
string e = "Joe said \"Hello\" to me"; // Joe said "Hello" to me
string f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to me
string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt
string h = @"\\server\share\file.txt"; // \\server\share\file.txt
string i = "one\r\ntwo\r\nthree";
string j = @"one
two
three";
string a = @"";
string b = "";
生成以下IL代码:
IL_0001: ldstr ""
IL_0006: stloc.0 // a
IL_0007: ldstr ""
IL_000C: stloc.1 // b
decimal x = 0.0m; decimal y = 0.00m; Console.Write("{0}, {1}, {2}", x, y, x == y);
- DavidG