What's the use/meaning of the @ character in v

2018-12-31 04:23发布

I discovered that you can start your variable name with a '@' character in C#. In my C# project I was using a web service (I added a web reference to my project) that was written in Java. One of the interface objects defined in the WSDL had a member variable with the name "params". Obviously this is a reserved word in C# so you can't have a class with a member variable with the name "params". The proxy object that was generated contained a property that looked like this:

public ArrayList @params {
    get { return this.paramsField; }
    set { this.paramsField = value; }
}

I searched through the VS 2008 c# documentation but couldn't find anything about it. Also searching Google didn't give me any useful answers. So what is the exact meaning or use of the '@' character in a variable/property name?

9条回答
只靠听说
2楼-- · 2018-12-31 05:23

Unlike Perl's sigils, an @ prefix before a variable name in C# has no meaning. If x is a variable, @x is another name for the same variable.

> string x = "abc";
> Object.ReferenceEquals(x, @x).Dump();
True

But the @ prefix does have a use, as you've discovered - you can use it to clarify variables names that C# would otherwise reject as illegal.

> string string;
Identifier expected; 'string' is a keyword

> string @string;
查看更多
永恒的永恒
3楼-- · 2018-12-31 05:25

Another use-case is in extension methods. The first, special parameter can be distinguished to denote its real meaning with @this name. An example:

public static TValue GetValueOrDefault<TKey, TValue>(
    this IDictionary<TKey, TValue> @this,
    TKey key,
    TValue defaultValue)
    {
        if (!@this.ContainsKey(key))
        {
            return defaultValue;
        }

        return @this[key];
    }
查看更多
孤独寂梦人
4楼-- · 2018-12-31 05:26

It simply allows you to use reserved words as variable names. I wanted a var called event the other day. I was going to go with _event instead, but my colleague reminded me that I could just call it @event instead.

查看更多
登录 后发表回答