15 전처리기

vencott·2021년 6월 2일
0

C#

목록 보기
15/32

전처리기 지시어(Preprocessor Directive)

컴파일이 시작되기 전에 컴파일러에게 특별한 명령을 미리 처리하도록 지시

C# Statement가 아니기 때문에 끝에 세미콜론을 붙이지 않는다

해당 파일 안에서만 효력을 발생한다

만약 하나의 클래스가 두개의 파일에 나뉘어 Partial Class로 저장되면 두개의 파일에 각각 명시해야 한다

C# 전처리기는 C/C++와 달리 별도의 Preprocessor를 갖지 않고 컴파일러가 Preprocessor Dirctive를 함께 처리한다

조건별 컴파일

#define

심벌을 정의할 때 사용

#define DEBUG
#define RELEASE

정의된 심벌은 다른 전처리기 지시어에서 사용

#if(DEBUG)

#if…#else…#endif

#define과 결합되어 조건별로 다른 코드 블록을 컴파일하도록 할 수 있다

#define TEST_ENV
//#define PROD_ENV

using System;

namespace App1
{
    class Program
    {
        static void Main(string[] args)
        {
            bool verbose = false;
            // ...

#if (TEST_ENV)
            Console.WriteLine("Test Environment: Verbose option is set.");
            verbose = true;
#else
            Console.WriteLine("Production");
#endif

            if (verbose)
            {
                //....
            }
        }
    }
}

#region

코드 블록을 논리적으로 묶을 때 사용

#endrigion과 쌍을 이루며 한 영역을 형성

class ClassA
{
    #region Public Methods        
    public void Run() { }
    public void Create() { }        
    #endregion

    #region Public Properties
    public int Id { get; set; }
    #endregion

    #region Privates
    private void Execute() { }
    #endregion
}

#pragma

표준 C# 전처리기 지시어가 아닌 컴파일러 제작업체에서 고유하게 만들어 사용할 수 있는 지시어

#prama warning: 경고메서지를 disable/enable

#pragma checksum: ASP.NET 페이지 디버깅을 위해 만들어진 것으로 ASPX 페이지의 파일 체크섬을 생성할 때 사용

#pragma warning disable 3021

namespace App1
{
    [System.CLSCompliant(false)] 
    class Program
    {
        static void Main(string[] args)
        {
            //...
        
#pragma warning disable
        if (false)
        {
            Console.WriteLine("TBD");
        }
#pragma warning restore
        
            //...
        }
    }
}

출처: http://www.csharpstudy.com/

profile
Backend Developer

0개의 댓글