6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

csharp > Conditional attribute

Last updated at Posted at 2015-07-29

UnityのTutorialなどでConditionalというキーワードを見かけた。

C#の機能らしい。

# define TRACE_ON
using System;
using System.Diagnostics;

public class Trace
{
    [Conditional("TRACE_ON")]
    public static void Msg(string msg)
    {
        Console.WriteLine(msg);
    }
}

public class ProgramClass
{
    static void Main()
    {
        Trace.Msg("Now in Main...");
        Console.WriteLine("Done.");
    }
}

TRACE_ONの#defineをコメントアウトするとTrace.Msg()が実行されなくなる。

上記のmicrosoftのリンクでは

Using Conditional is a cleaner, more elegant, and less error-prone alternative to enclosing methods inside ,

ただ、複数の条件をANDで使うときは、下記のようにコードが冗長になるような気がする。

[Conditional("A")]
static void DoIfA()
{
    DoIfAandB();
}

[Conditional("B")]
static void DoIfAandB()
{
    // Code to execute when both A and B are defined...
}

これは#if defined()を使う方がいいかも。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?