空字符串文本
本文关键字:文本 字符串 | 更新日期: 2023-09-27 17:55:40
我在代码审查期间遇到了一些代码,一位老同事做了以下工作:
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
所以不,没有区别。