开发者

C# strudel sign

开发者 https://www.devze.com 2023-01-17 10:21 出处:网络
While coding in C#, I by mistake added a strudel sign before a variable in if statement (instead of exclam开发者_如何转开发ation mark).

While coding in C#, I by mistake added a strudel sign before a variable in if statement (instead of exclam开发者_如何转开发ation mark).

bool b = false;
if (@b)
{

}

I surprised it compiled successfully without any error.

I wonder: What is the meaning of the above code?


@ can be used to "escape" identifiers, in case you want to use keywords. For example:

int @class = 10;

Of course it's usually a bad idea to use keywords as identifiers, but if you're using a class library which happens to use them, it can be hard to avoid. It can also be useful sometimes to use "@this" for situations where you want to effectively have a this reference, but for whatever reason you can't use one. (These are pretty few and far between, but I've seen it a couple of times, and it's worth at least knowing about.)


Jon's answer sums it up. An example of when you must use this technique of escaping is specifying HTML attributes in anonymous types to helper methods in ASP.NET MVC.

Html.ActionLink("text", "action", "controller",
    new { @class = "some-css-class" }, null);

I've also hit this when composing anonymous types for posting via HTTP using JSON encoding, where you cannot modify the remote API.

+1 for 'strudel' too :)

0

精彩评论

暂无评论...
验证码 换一张
取 消