【问题标题】:How the Conditional Attribute works behind the scenes条件属性如何在幕后工作
【发布时间】:2014-01-13 22:52:42
【问题描述】:

我们有这个代码:

public static class MyCLass 
{
    [Conditional("Debugging")]  
    public static void MyMethod()
    {
         Console.WriteLine("Example method");
    }
}
.
.
.
//In debug mode: Executing Main method in debug mode
MyClass.MyMethod()

我只想知道条件属性如何改变 MyMethod 的行为,假设在 .NET 中条件属性定义为:

public class Conditional: Attribute
{
   .
   .
   public string Mode { get; set; )
   .
   .
   public Conditional(string Mode)
   {
       .
       .
       this.Mode = Mode;
       if (Mode == "Debugging")
       {
          #ifdef DEBUG
          //HOW THE CONDITIONAL CONSTRUCTOR COULD CHANGE THE BEHAVIOUR OF MyMethod
          #endif
       }
       .
       .
   }
}

如何访问由我的属性(即来自 MyAttribute 类)修饰的资源(方法、成员、类..)?

【问题讨论】:

  • 剧透:它被硬编码到编译器中。

标签: c# .net debugging conditional custom-attributes


【解决方案1】:

该属性告诉编译器查看是否设置了标志,如果没有设置,则不会编译对该方法的任何调用,就好像该方法调用从未存在于代码中一样。您可以使用 ILSpy 等反射器工具轻松看到这一点。

所以实际上并不是属性改变了方法的行为,而是知道查找该属性并相应地改变其行为的编译器。

属性方法(在您的情况下为MyMethod)仍在编译,可以通过反射访问。

【讨论】:

    猜你喜欢
    • 2016-08-05
    • 1970-01-01
    • 2014-07-12
    • 2023-03-26
    • 2020-12-23
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多