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)
13490정성태12/19/20232399개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232178개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232115오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232416개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232233개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232123오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232201개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232340닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20233012닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232316개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232711개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232376개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232628닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232321닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232417닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232234개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232512닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232251C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232362Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232686닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232455닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232342닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232454오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232620닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232361개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232496닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...