when to use @ in c#?

前端 未结 5 1158
春和景丽
春和景丽 2020-12-06 04:44

I use @ symbol with local path only, but when do I use @ exactly?

5条回答
  •  误落风尘
    2020-12-06 05:18

    Verbatim Strings

    An @ before a string literal in C# denotes a verbatim string. In a verbatim string, only the quote escape sequence ("") is parsed as an escape sequence; all others, e.g. \n, \t etc. are ignored.

    You'll have seen this syntax used with file paths, etc. because it's convenient to have the compiler ignore the backslashes in the path, rather than having to double-escape them, e.g.

    var s = @"c:\Some\File\Path.txt";
    

    is a little easier to read than

    var s = "c:\\Some\\File\\Path.txt";
    

    Reserved Words

    You can also prefix identifiers with @ in order to allow using reserved words in identifiers. For example, @class can be used as an identifier, whereas class wouldn't be permitted. In this specific case, @class is a little less jarring (at least, I find) than the usual convention of klass or clazz which are often used to work around this restriction in other languages.

提交回复
热议问题