본문 바로가기

C#

[ C# ]Conditional Attribute

[ Conditional Attribute ]

[ #if / #endif의 단점 ]

=> #if / #endif 로 묶는다면 메서드를 묶는다면 메서드 내용이 포함되지는 않지만 쓸데없는 메서드의 호출은 피할 수 없다 .

또한 코더의 실수를 유발하여 , 의도하지 않은 코드가 삽입 될 수 있다 .

=>이러한 단점을 개선시킬 방법이 Conditional 어트리뷰트이다 .

 

[ Conditional ]

=>c#에서 사용 가능한 조건부 컴파일 기호이다 . Release 모드에서 메서드 내용이 컴파일 되지만 호출되지 않으며 ,

메서드 전체에 대한 제어가 가능하다 . 그래서 #if/#endif보다 좋은 성능을 기대 할 수 있다 .

 

=>단, void메서드에서만 가능하며 , 메서드 일부가 아닌 전체에만 지정이 가능하다 .

 

[ 사용 예시 ]

#define CONDITION1
#define CONDITION2
using System;
using System.Diagnostics;

class Test
{
    static void Main()
    {
        Console.WriteLine("Calling Method1");
        Method1(3);
        Console.WriteLine("Calling Method2");
        Method2();

        Console.WriteLine("Using the Debug class");
        Debug.Listeners.Add(new ConsoleTraceListener());
        Debug.WriteLine("DEBUG is defined");
    }

    [Conditional("CONDITION1")]
    public static void Method1(int x)
    {
        Console.WriteLine("CONDITION1 is defined");
    }

    [Conditional("CONDITION1"), Conditional("CONDITION2")]
    public static void Method2()
    {
        Console.WriteLine("CONDITION1 or CONDITION2 is defined");
    }
}

/*
When compiled as shown, the application (named ConsoleApp)
produces the following output.

Calling Method1
CONDITION1 is defined
Calling Method2
CONDITION1 or CONDITION2 is defined
Using the Debug class
DEBUG is defined
*/

 

[ 플랫폼별 지시어 사용 ]

=>유니티의 경우 플랫폼별 지시어를 활용 , 여러 기능이 가능하다 .

예를 들어 에디터상에서만 Debug를 띄울 수 있다 .

[System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void Log(object msg)
{
	Debug.Log(msg);
}

=>이때 , using System.Diagonstics를 하지 않는 이유는 UnityEngine.Debug를 Debug.Log(""); 이런식으로 사용하면

System.Diagonstics의 Debug와 충돌이 나 , 일일이 UnityEngine.Debug를 해줘야 하기에 위처럼 직접 입력하여 사용한다 .

 

 

참조

나날이 스튜디오 블로그

유니티 문서 - 조건부 컴파일

MS문서 - Conditional