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

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13606정성태4/24/202498닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024328닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024349오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024600닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024797닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024838닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024848닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024862닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024884닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024867닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241052닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241050닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241068닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241079닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241218C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241196닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241078Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241150닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241263닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241168오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241329Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241112Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241063개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241302Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241559Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...