Csharp/CSharp Tutorial/Attribute/Conditional Attribute

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Demonstrate the Conditional attribute

#define TRIAL 
 
using System; 
using System.Diagnostics; 
 
class MainClass { 
 
  [Conditional("TRIAL")]  
  void trial() { 
    Console.WriteLine("Trial version, not for distribution."); 
  } 
 
  [Conditional("RELEASE")]  
  void release() { 
    Console.WriteLine("Final release version."); 
  } 
 
  public static void Main() { 
    MainClass t = new MainClass(); 
 
    t.trial(); // call only if TRIAL is defined 
    t.release(); // called only if RELEASE is defined 
  } 
}
Trial version, not for distribution.

The Conditional Attribute

  1. The Conditional Attribute allows you to create conditional methods.
  2. A conditional method is invoked only when a specific symbol has been defined via #define.
  3. Otherwise, the method is bypassed.
  4. A conditional method offers an alternative to conditional compilation using #if.
  5. Conditional is another name for System.Diagnostics.ConditionalAttribute.
  6. To use the Conditional attribute, you must include the System.Diagnostics namespace.

Conditional methods have a few restrictions.

  1. Conditional methods must return void.
  2. Conditional methods must be members of a class, not an interface.
  3. Conditional methods cannot be preceded with the override keyword.

10.3.Conditional Attribute 10.3.1. The Conditional Attribute 10.3.2. <A href="/Tutorial/CSharp/0200__Attribute/DemonstratetheConditionalattribute.htm">Demonstrate the Conditional attribute</a> 10.3.3. <A href="/Tutorial/CSharp/0200__Attribute/TheConditionalattributesettinginCompileparameter.htm">The Conditional attribute setting in Compile parameter</a>

The Conditional attribute setting in Compile parameter

// csc /define:DEBUG MainClass.cs
using System;
using System.Diagnostics;  
public class MyClass {
  [Conditional("DEBUG")]
  public void OnlyWhenDebugIsDefined( ) {
    Console.WriteLine("DEBUG is defined");
  }
}

public class MainClass {
  public static void Main( ) {
    MyClass f = new MyClass( );
    f.OnlyWhenDebugIsDefined( );
  }
}