logo search
CSharp_Prog_Guide

Общие атрибуты

В этом разделе описаны атрибуты, наиболее часто используемые в программах на языке C#.

Conditional

Делает выполнение метода зависимым от идентификатора предварительной обработки. Атрибут Conditional является псевдонимом для ConditionalAttribute и может применяться к методу или атрибуту class.

В данном примере атрибут Conditional применяется к методу для включения и отключения отображения диагностической информации для конкретной программы:

----

Если идентификатор TRACE_ON не задан, выходные данные трассировки не отображаются.

Атрибут Conditional часто используется с идентификатором DEBUG для разрешения функций трассировки и ведения журнала в построениях отладки, но не в построениях выпуска:

[Conditional("DEBUG")]

static void DebugMethod()

{

}

Remarks

When a method marked as conditional is called, the presence or absence of the specified preprocessing symbol determines whether the call is included or omitted. If the symbol is defined, the call is included; otherwise, the call is omitted. Using Conditional is a cleaner, more elegant, and less error-prone alternative to enclosing methods inside #if and #endif, like this:

#if DEBUG

void ConditionalMethod()

{

}

#endif

A conditional method must be a method in a class or struct declaration and must have a return type of void.

Using multiple identifiers

If a method has multiple Conditional attributes, a call to the method is included if at least one of the conditional symbols is defined (in other words, the symbols are logically ORed together). In this example, the presence of either A or B will result in a method call:

[Conditional("A"), Conditional("B")]

static void DoIfAorB()

{

// ...

}

To achieve the effect of logically ANDing symbols, you can define serial conditional methods. For example, the second method below will execute only if both A and B are defined:

[Conditional("A")]

static void DoIfA()

{

DoIfAandB();

}

[Conditional("B")]

static void DoIfAandB()

{

// Code to execute when both A and B are defined...

}