简体   繁体   中英

What is DiscardableAttribute used for?

I can not find the practical use of System.Runtime.CompilerServices.DiscardableAttribute , even for a prototype compiler. Any insight? Thanks.

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):

static class Bar {
  static inline void Foo(int a) { // Note fictional 'inline' modifier
    return a + 10;
  }
}

If you have a class like this, it isn't really referenced by any other piece of your code. When you write:

int y = Bar.Foo(x);

The compiler compiles it as:

int y = x + 10;

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 the Foo 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 as Discardable and the JIT could possibly skip it when generating native code for your assembly (because the class will never be used).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM