What other neat tricks does the SpecialNameAttribu

2020-08-22 03:10发布

问题:

In researching a question on implementing the Visual Basic Power (^) operator, I learned that the System.Runtime.CompilerServices.SpecialNameAttribute class allows one to implement this operator in C# for use in VB.

Interestingly, the documentation states:

The SpecialNameAttribute class is not currently used in the .NET Framework, but is reserved for future use.

My question is: What other neat tricks are available when using this attribute?

(side question - is the documentation inaccurate or is this a semantic issue since the attribute is apparently used by the compiler but not the framework?)

回答1:

As you can tell when looking at the generated IL from that code, the compiler uses the attribute to turn on the specialname IL attribute on the method declaration. The best place to look for its use is the ECMA 335 CLI specification.

In general, it is used to mark the identifier as having special usage. You'll see it turn on for example on the getter and setter method of a property, event accessor methods and operator overloads. Note the distinction with the rtspecialname IL attribute, the specialname attribute affects tools and not the jitter. Like the VB.NET compiler in this case which now distinguishes op_Exponent() as an operator overload instead of just a plain method with a funny name.

Do note that this is all baked-in behavior, you can't pull tricks that the compiler and jitter were not programmed to recognize.