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

... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12208정성태4/12/20209970Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/20208954스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202011253오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/20208642스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/20208458스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202010487오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202013112개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202010912오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202011333VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/20209182오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202011931오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202011078VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/20208998오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202010716.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202013034오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/20209724개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202012173개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202012535개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/20208647오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202013492개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202015803Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/20208470오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/20209564오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202010242오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202011646오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/202010014오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...