简体   繁体   中英

What's the meaning of “@” in C#

new learner's quick question, what's the meaning of "@" in C# codes?

Examples:

ClientDataSource.Where = @"it.ClientID==1";
cont.Notes = @"";
Response.Redirect(@"~/Default.aspx");

Thanks!

That is a verbatim string literal .

MSDN describes it as such :

Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string.

@ can also be used to create identifiers that match reserved words: 2.4.2 Identifiers

For example:

var class = "Reading"; // compiler error
var @class = "Math"; // works

@"...." denotes a verbatim string literal . C# does not process any escape characters in the string, except for "" (to allow including of the " character in the string).

This makes it easier and cleaner to handle strings that would otherwise need to have a bunch of escapes to deal with properly. File/folders paths, for example.

string filePathRegular = "C:\\Windows\\foo\\bar.txt";
string filePathVerbatim = @"C:\Windows\foo\bar.txt";

It's also very useful in writing Regular Expressions, and probably many other things.

It's worth noting that C# also uses the @ character as a prefix to allow reserved words to be used as identifiers. For example, Html Helpers in ASP.Net MVC can take an anonymous object containing HTML attributes for the tags they create. So you might see code like this:

<%= Html.LabelFor(m => m.Foo, new { @class = "some-css-class" } ) %>

The @ is needed here because class is otherwise a reserved word.

The verbatim string literal allows you to put text inside of a string that would otherwise be treated differently by the compiler. For example, if I were going to write a file path and assign it to a variable, I might do something like so:

myString = "C:\\Temp\\Test.txt";

The reason I have to have the double slashes is because I am escaping out the slash so it isn't treated as an command. If I use the verbatim string literal symbol, my code could look as follows:

myString = @"C:\Temp\Test.txt";

It makes it easier to write strings when you are dealing with special characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM