DiscardableAttribute 有何用途?
我找不到 System.Runtime.CompilerServices.DiscardableAttribute 的实际用途,即使对于原型编译器也是如此。有什么见解吗?
I can not find the practical use of System.Runtime.CompilerServices.DiscardableAttribute
, even for a prototype compiler. Any insight?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
举一个比文档所述更具体的示例 - 您可以拥有一种支持内联静态方法调用的语言,这些静态方法调用使用某些特殊修饰符(来自静态类)进行标记:
如果您有这样的类,则它不是确实被任何其他代码片段引用。当您编写时:
编译器将其编译为:
您需要在编译的代码中保留
Bar
的定义,因为如果您从其他项目引用程序集,您希望看到它(并且当您然后调用 Foo 方法,编译器只会从该程序集中获取已编译的 IL)。但是,类
Bar
永远不会在运行时使用(它只是为了保留代码,而不是实际执行它)。我想您可以将其标记为“Discardable”,并且 JIT 在为程序集生成本机代码时可能会跳过它(因为该类永远不会被使用)。To give a more specific example than what the documentation says - you could have a language that supports inlining of static method calls that are marked using some special modifier (from a static class):
If you have a class like this, it isn't really referenced by any other piece of your code. When you write:
The compiler compiles it as:
You need to keep the definition of
Bar
in the compiled code, because if you reference the assembly from some other project, you want to see it (and when you then call theFoo
method, the compiler will just take compiled IL from that assembly).However, the class
Bar
would never be used at runtime (it is there just to keep the code, but not to actually execute it). I imagine you could mark it asDiscardable
and the JIT could possibly skip it when generating native code for your assembly (because the class will never be used).