Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

C# 5의 Caller Info를 .NET 4.5 미만의 응용 프로그램에 적용하는 방법

CallerInfo에 대해 예전에 한번 소개해 드렸는데요.

C# 5.0 에 새로 추가된 Caller Info 특성
; https://www.sysnet.pe.kr/2/0/1134

C# 코드 구문으로는 다음과 같이 사용하지만,

public static class MyExt
{
    public static void Write(string msg, [CallerMemberName] string method = "")
    {
        Console.WriteLine(string.Format("{0}:{1}", method, msg));
    }

    public void Test()
    {
        MyExt.Write("test");
    }
}

C# 컴파일러는 결국 다음과 같은 식으로 변환해서 컴파일하는 것에 불과합니다.

public static class MyExt
{
    public static void Write(string msg, [CallerMemberName] string method)
    {
        Console.WriteLine(string.Format("{0}:{1}", method, msg));
    }

    public void MyMethod()
    {
        MyExt.Write("test", "MyMethod");
    }
}

변환된 이 코드는, C# 5 버전과 아무런 종속 관계가 없습니다. 그래서, Caller Info를 사용한 코드가 담긴 프로젝트의 "TargetFramework" 속성을 ".NET 3.5"로 바꿔 컴파일해도 생성된 바이너리는 정상적으로 CLR 2 기반에서 잘 동작합니다.

단지, .NET 4.0 이하의 경우 mscorlib.dll에 CallerMemberNameAttribute 타입이 정의되어 있지 않기 때문에 빌드 에러를 피하기 위해 다음과 같이 임의로 만들어 포함해야 합니다.

namespace System.Runtime.CompilerServices
{
    using System;

    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public sealed class CallerMemberNameAttribute : Attribute
    {
    }

    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CallerFilePathAttribute : Attribute
    {
    }
 
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CallerLineNumberAttribute : Attribute
    {
    }
}

public static class MyExt
{
    public static void Write(string msg, [CallerMemberName] string method = "")
    {
        Console.WriteLine(string.Format("{0}:{1}", method, msg));
    }

    public void MyMethod()
    {
        MyExt.Write("test", "MyMethod");
    }
}

이런 내용들이 다음의 글에 잘 포함되어 있습니다.

Using C# 5 caller info attributes when targeting earlier versions of the .NET framework
; http://www.thomaslevesque.com/2012/06/13/using-c-5-caller-info-attributes-when-targeting-earlier-versions-of-the-net-framework/

그런데, 같은 소스 코드를 닷넷 버전별로 컴파일하고 싶다면 어떻게 해야 할까요? 이런 경우 전처리기 지시자를 사용하면 됩니다. 가령 다음과 같은 식입니다.

using System;
using System.Runtime.CompilerServices;

#if BELOW45

namespace System.Runtime.CompilerServices
{
    using System;

    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    public sealed class CallerMemberNameAttribute : Attribute
    {
    }

    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CallerFilePathAttribute : Attribute
    {
    }
 
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CallerLineNumberAttribute : Attribute
    {
    }
}

#endif

class NormalProgram
{
    static void Main(string[] args)
    {
        // ...[생략]...
    }
}

.NET 2.0 ~ 4로 컴파일할 땐 BELOW45 상수를 정의하고 4.5 이상인 경우에는 상수 정의를 없애주면 됩니다. msbuild.exe로 빌드한다면 다음과 같이 나눠서 빌드하면 됩니다.

// ---------------------------- C# 5.0 컴파일러로 2가지 상황에 따라 빌드

// .NET 2.0 ~ 4.0
msbuild MyTest.csproj /p:DefineConstants="BELOW45;TRACE" /t:Rebuild /p:TargetFrameworkVersion=v3.5

// .NET 4.5 or later
msbuild MyTest.csproj /t:Rebuild




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/16/2016]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2016-02-15 02시12분
[spowner] 이해하기도 쉽고 유용한 정보입니다. 감사합니다
[guest]
2016-02-15 10시23분
제가 지식의 부족도 문제지만 제 고정관념이 더 큰 문제였단 걸 배우고 갑니다. 좋은 글 감사드립니다. 정말 큰 도움이 되었습니다^^
Beren Ko
2016-02-16 01시07분
출근하면서 곰곰히 생각해보니 CallerMemberName을 사용할 수 있는 상황이라 함에도 인라인 처리되면 알려주신 방법으로 해결이 될까 싶어서 테스트를 해 보았습니다.
좀 길긴 하지만 Scott Hanselman이 Release is not Debug 글에서 사용했던 샘플을 이용해서 테스트 한 걸 옮겨보겠습니다.

using System;
using System.Runtime.CompilerServices;

class NormalProgram
{
    static string s = string.Empty;

    static void Main(string[] args)
    {
        try
        {
            methodA();
        }
        catch (System.Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
    
    
    static void methodA([CallerMemberName]string prevMethodName = "") { s += prevMethodName + "\r\n"; methodB(); }


    static void methodB([CallerMemberName]string prevMethodName = "") { s += prevMethodName + "\r\n"; methodC(); }


    static void methodC([CallerMemberName]string prevMethodName = "") { s+= prevMethodName; badMethod(); }

    static void badMethod() { Console.WriteLine(s); throw new ApplicationException("generic bad thing"); }
}

제 걱정은 인라인 처리되면 스택정보도 없이 메서드가 상위메서드에 포함되어버릴텐데 CallerMemberName이 유효하게 소스에서의 S에 추가가 될까? 라는 의문이었습니다.
그런데 위의 실행 결과를 보면

C:\Test>NormalRelease.exe
Main
methodA
methodB
System.ApplicationException: generic bad thing
   위치: NormalProgram.badMethod() 파일 c:\CSharpStudy\NormalProgram.cs:줄 29
   위치: NormalProgram.Main(String[] args) 파일 c:\CSharpStudy\NormalProgram.cs:줄 12

위와 같은 결과가 나옵니다.
즉 인라인 처리가 된다 하더라도 메서드명은 CallerMemberName이 적용된 변수에 담아주었던 것이네요^^
Beren Ko
2016-02-16 01시32분
당연한 결과입니다. ^^ 컴파일 타임에 이미 문자열을 전달한 코드가 박혀 있기 때문에 런타임에 인라인되어도 그 코드는 유효하게 인라인 처리되니까요.
정성태
2016-02-16 01시45분
네~ 다시 생각해보니 당연한 말씀이네요. 컴파일 된 결과를 리플렉터로 확인해보아도 말씀하신 바를 확인할 수 있었구요. 가르침 감사합니다^^
Beren Ko

... 31  32  33  34  35  36  37  [38]  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12699정성태7/8/20217884VS.NET IDE: 167. Visual Studio 디버깅 중 GC Heap 상태를 보여주는 "Show Diagnostic Tools" 메뉴 사용법
12698정성태7/7/202111848오류 유형: 732. Windows 11 업데이트 시 3% 또는 0%에서 다운로드가 멈춘 경우
12697정성태7/7/20217690개발 환경 구성: 574. Windows 11 (Insider Preview) 설치하는 방법
12696정성태7/6/20218318VC++: 146. 운영체제의 스레드 문맥 교환(Context Switch)을 유사하게 구현하는 방법파일 다운로드2
12695정성태7/3/20218375VC++: 145. C 언어의 setjmp/longjmp 기능을 Thread Context를 이용해 유사하게 구현하는 방법파일 다운로드1
12694정성태7/2/202110383Java: 24. Azure - Spring Boot 앱을 Java SE(Embedded Web Server)로 호스팅 시 로그 파일 남기는 방법 [1]
12693정성태6/30/20218056오류 유형: 731. Azure Web App Site Extension - Failed to install web app extension [...]. {1}
12692정성태6/30/20217984디버깅 기술: 180. Azure - Web App의 비정상 종료 시 남겨지는 로그 확인
12691정성태6/30/20218737개발 환경 구성: 573. 테스트 용도이지만 테스트에 적합하지 않은 Azure D1 공유(shared) 요금제
12690정성태6/28/20219591Java: 23. Azure - 자바(Java)로 만드는 Web App Service - Tomcat 호스팅
12689정성태6/25/202110203오류 유형: 730. Windows Forms 디자이너 - The class Form1 can be designed, but is not the first class in the file. [1]
12688정성태6/24/20219864.NET Framework: 1073. C# - JSON 역/직렬화 시 리플렉션 손실을 없애는 JsonSrcGen [2]파일 다운로드1
12687정성태6/22/20217785오류 유형: 729. Invalid data: Invalid artifact, java se app service only supports .jar artifact
12686정성태6/21/202110292Java: 22. Azure - 자바(Java)로 만드는 Web App Service - Java SE (Embedded Web Server) 호스팅
12685정성태6/21/202110528Java: 21. Azure Web App Service에 배포된 Java 프로세스의 메모리 및 힙(Heap) 덤프 뜨는 방법
12684정성태6/19/20218970오류 유형: 728. Visual Studio 2022부터 DTE.get_Properties 속성 접근 시 System.MissingMethodException 예외 발생
12683정성태6/18/202110441VS.NET IDE: 166. Visual Studio 2022 - Windows Forms 프로젝트의 x86 DLL 컨트롤이 Designer에서 오류가 발생하는 문제 [1]파일 다운로드1
12682정성태6/18/20218066VS.NET IDE: 165. Visual Studio 2022를 위한 Extension 마이그레이션
12681정성태6/18/20217421오류 유형: 727. .NET 2.0 ~ 3.5 + x64 환경에서 System.EnterpriseServices 참조 시 CS8012 경고
12680정성태6/18/20218564오류 유형: 726. python2.7.exe 실행 시 0xc000007b 오류
12679정성태6/18/20219085COM 개체 관련: 23. CoInitializeSecurity의 전역 설정을 재정의하는 CoSetProxyBlanket 함수 사용법파일 다운로드1
12678정성태6/17/20218281.NET Framework: 1072. C# - CoCreateInstance 관련 Inteop 오류 정리파일 다운로드1
12677정성태6/17/20219923VC++: 144. 역공학을 통한 lxssmanager.dll의 ILxssSession 사용법 분석파일 다운로드1
12676정성태6/16/20219816VC++: 143. ionescu007/lxss github repo에 공개된 lxssmanager.dll의 CLSID_LxssUserSession/IID_ILxssSession 사용법파일 다운로드1
12675정성태6/16/20217882Java: 20. maven package 명령어 결과물로 (war가 아닌) jar 생성 방법
12674정성태6/15/20218768VC++: 142. DEFINE_GUID 사용법
... 31  32  33  34  35  36  37  [38]  39  40  41  42  43  44  45  ...