我有一个ReSharper的试用版本,它总是建议我将常规字符串转换为逐字字符串。有什么关系?
发布于 2010-07-23 02:19:14
逐字字符串是不需要转义的字符串,如文件名:
string myFileName = "C:\\myfolder\\myfile.txt";
将会是
string myFileName = @"C:\myfolder\myfile.txt";
@符号表示按字面意思读取字符串,否则不会解释控制字符。
发布于 2010-07-23 02:39:54
字符串和逐字字符串在运行时没有区别。它们只是在编译时有所不同。编译器在逐字字符串中接受较少的转义序列,因此除了引号转义之外,您所看到的就是您所获得的。
您还可以使用逐字字符@来告诉编译器将关键字视为名称:
var @if = "if";
//okay, treated as a name
Console.WriteLine(@if);
//compiler err, if without @ is a keyword
Console.WriteLine(if);
var @a = "a";
//okay
Console.WriteLine(@a);
//also okay, @ isn't part of the name
Console.WriteLine(a);
发布于 2010-07-23 02:21:55
常规字符串使用特殊的转义序列来转换为特殊字符。
/*
This string contains a newline
and a tab and an escaped backslash\
*/
Console.WriteLine("This string contains a newline\nand a tab\tand an escaped backslash\\");
逐字字符串按原样解释,不转换任何转义序列:
/*
This string displays as is. No newlines\n, tabs\t or backslash-escapes\\.
*/
Console.WriteLine(@"This string displays as is. No newlines\n, tabs\t or backslash-escapes\\.");
https://stackoverflow.com/questions/3311988
复制相似问题