C#中@字符的用途 [英] purpose of the @ character in C#
问题描述
你好,
我已经使用C#进行了一段时间的实验,但我一直看到@字符,但找不到确切的功能.
我看到它在文件路径中使用了,今天,我在其他地方看到了它,无法确定目的.
有人可以解释@字符的确切含义/目的/用途是什么吗?
我在其中看到过的代码段:
Hello,
I''ve been experimenting with C# for some time now, and I keep seeing the @ character and can not find what it does exactly.
I saw it beeing used in file paths, and today I saw it somewhere else and could not figure the purpose.
Can someone explain what the exact meaning/purpose/use of the @ character is?
Code snippets where I saw it used:
string SoftwareKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
if (printerName.Equals(@"hp deskjet 930c"))
private string sbfFilePath = Application.StartupPath + @"\lukas.sbf";
推荐答案
在上述所有情况下,@均用于允许转义字符.
如果你写这个
In all above cases @ is used to allow escape character.
If you write this
string SoftwareKey = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
它将给您语法错误.
因此您可以使用此
It will give you syntax error.
So you can use this
string SoftwareKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
这是困难的方法,因此
This is difficult way so instead
string SoftwareKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
现在整体使用@
您可以使用reserverd关键字
1.
Now overall use of @
You can use reserverd keyword
1.
string for;
是不允许的,但在下面允许输入代码
is not allowed but below code is allowed
string @for;
2.如上例所示,允许转义字符.
3.使用多行文字
2.To allow escape character as above example.
3.To use multiline text
Label1.Text="First line \n Second Line ";
对此用途进行了安装
Insted of this use this
Label1.Text= @"First line
Second Line ";
因此,这里的@符号取其写法.
So here @ sign take line how it is written.
字符串前的"@"字符会关闭转义字符.没有它,任何跟在"\"字符之后的字符都将被解释为特殊代码:
The ''@'' character before a string turns off character escaping. Without it, any character following a ''\'' character is interpreted as a special code:
\n Newline
\t Tab
\\ A single '\' character
\" A single '"' character
等等.
所以
and so on.
So
string s = "\\\"\\\"";
将为您提供包含以下内容的字符串:
would give you a string containing:
A backslash
A doublequote
A backslash
A doublequote
在其前面加上"@"可将其关闭:
Prefixing it with ''@'' turns that off:
string s = @"\""\";
将为您提供相同的结果,这使得路径,正则表达式等更具可读性:
Will give you the same result, which makes paths, regexes and so forth a lot more readable:
@"D:\Temp\MyFile.txt"
与
相反
"D:\\Temp\\MyFile.text"
如果关闭转义,要输入双引号,请同时输入两个:
If you turn off escaping, to enter a double quote, you enter two of them together:
string s = "hello ""Paul"" - this is a string"
这篇关于C#中@字符的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!