简体   繁体   English

为什么C#编译器将il代码留给条件方法?

[英]Why does c# compiler leave il code for conditional method?

I have following program: 我有以下程序:

public class TestClass
{
   [Conditional("DEBUG")]
   static void debug_foo()
   {
       Console.WriteLine("DEBUG foo");
   }
   static int Main(System.String[] args)
   {
       debug_foo();
       return 0;
   }
}

I compiled program using Release mode. 我使用发布模式编译程序。 I found il code of debug_foo method in assembly. 我在汇编中找到了debug_foo方法的il代码。 I cannot understand reason of such solution. 我不明白这种解决方案的原因。 I thought that if c# compiler can understand, that method is not used, then compiler need not to generate il code at all (for example, it will not generate call instruction in main function), beacuse it slows compilation and increase size of assembly. 我认为如果c#编译器可以理解,则不使用该方法,那么编译器根本不需要生成il代码(例如,它将不会在main函数中生成调用指令),因为它会减慢编译速度并增加程序集的大小。

The method logically still exists, and could be called by reflection, for example. 该方法在逻辑上仍然存在,例如可以通过反射调用。

The C# 5 specification only talks about the calls being omitted - nothing about the implementation being omitted (section 17.4.2): C#5规范讨论忽略了调用-没有忽略实现(第17.4.2节):

A method decorated with the Conditional attribute is a conditional method. Conditional属性修饰的方法是条件方法。 The Conditional attribute indicates a condition by testing a conditional compilation symbol. Conditional属性通过测试条件编译符号来指示条件。 Calls to a conditional method are either included or omitted depending on whether this symbol is defined at the point of the call. 根据是否在调用时定义了此符号,可以包含或省略对条件方法的调用。 If the symbol is defined, the call is included; 如果定义了该符号,则包括该呼叫; otherwise, the call (including evaluation of the receiver and parameters of the call) is omitted. 否则,将忽略该呼叫(包括对接收方的评估和该呼叫的参数)。

Additionally, there are other situations (eg inheritance, or if the method were public) where it would still need to be present. 此外,在其他情况下(例如继承或方法是公开的),仍然需要使用它。 Simply always keeping the method in IL is much simpler than expressing in the specification all situations in which it can be omitted. 始终将方法保持在IL中比在规范中表达所有可以省略的情况要简单得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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