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)
13542정성태1/30/20241920오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241984VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242124Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242379개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242441닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242553닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242606닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242493닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242262닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242501닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242374닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242318닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242220닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242100닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242246Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242160오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242250닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242213오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242301오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242101오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242243닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242313닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242081오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242146닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242390닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242221스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...