C# Alias an Attribute (such as Inline Hinting)

六眼飞鱼酱① 提交于 2019-12-12 00:38:29

问题


I've been wanting for a while to shorten the (no-using-pollution) "inline" attribute from the absurdity that is:
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
to, well, [InlineHint] or [MyCompilerSvcs.InlineHint] or similar- something both quicker to type and quicker to mentally parse.

Is there any way to actually do that? Right now the only "sane" options I can see are to either add using System.Runtime.CompilerServices; (which is a pain when dealing with code behind of an ASP.NET website), adding more specific using aliases (even worse), or to keep it long-form in an accessible location for copy-paste.

Providing this question from 2009 isn't too outdated, using seems to be the only way to shorten how large the attribute reference is (as nobody suggested a more keyword-like variant for large, multifile projects). This related question was from 2010, and also suggests a using trick.

From 2015, there was this question, but it was in reference to the resulting decorations. Since what I'm interested in is the compiler directives themselves (and a performance-based one at that!) I doubt a runtime IL Emit could do this, and a "code bridge" doesn't quite naturally extend to compiler services in my mind.

Currently targeting C# 4.5, but newer versions are not forbidden.

And before "The compiler does inlining automatically!", it only does so for 32 IL Bytes or less and the inline hint overrides the size restriction. There are also other options which could be useful to have more accessible, such as NoOptimization, NoInline, and Synchronized, all of which I would very much like to not have to type absurdly long attributes to access without using statements.


回答1:


You can write a Roslyn-based tool to do that. This enables to apply an attribute with a name of your choice (some short name such as AggInline) and the tool will emit the actual AggressiveInlining attribute and the required using directives. You can see the ImmutableObjectGraph tool as an example on how to do something like that in Roslyn.



来源:https://stackoverflow.com/questions/41556273/c-sharp-alias-an-attribute-such-as-inline-hinting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!