What's the @ in front of a string in C#?
This is a .NET question for C# (or possibly VB.net), but I am trying to figure out what's the difference between the following declarations:
string hello = "hello";
vs.
string hello_alias = @"hello";
Printing out on the console makes no difference, the length properties are the same.
It marks the string as a verbatim string literal - anything in the string that would normally be interpreted as an escape sequence is ignored.
So "C:UsersRich"
is the same as @"C:UsersRich"
There is one exception: an escape sequence is needed for the double quote. To escape a double quote, you need to put two double quotes in a row. For instance, @""""
evaluates to "
.
It's a verbatim string literal. It means that escaping isn't applied. For instance:
string verbatim = @"foobar";
string regular = "foobar";
Here verbatim
and regular
have the same contents.
It also allows multi-line contents - which can be very handy for SQL:
string select = @"
SELECT Foo
FROM Bar
WHERE Name='Baz'";
The one bit of escaping which is necessary for verbatim string literals is to get a double quote (") which you do by doubling it:
string verbatim = @"He said, ""Would you like some coffee?"" and left.";
string regular = "He said, "Would you like some coffee?" and left.";
An '@' has another meaning as well: putting it in front of a variable declaration allows you to use reserved keywords as variable names.
For example:
string @class = "something";
int @object = 1;
I've only found one or two legitimate uses for this. Mainly in ASP.NET MVC when you want to do something like this:
<%= Html.ActionLink("Text", "Action", "Controller", null, new { @class = "some_css_class" })%>
Which would produce an HTML link like:
<a href="/Controller/Action" class="some_css_class">Text</a>
Otherwise you would have to use 'Class', which isn't a reserved keyword but the uppercase 'C' does not follow HTML standards and just doesn't look right.
链接地址: http://www.djcxy.com/p/20310.html上一篇: 计数字符数组中的字符
下一篇: C#中字符串前的@是什么?