Microsoft MVP성태의 닷넷 이야기
.NET Framework: 650. C# - CachedAnonymousMethodDelegate 유형의 코드 생성 [링크 복사], [링크+제목 복사]
조회: 13041
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

C# - CachedAnonymousMethodDelegate 유형의 코드 생성

C# 문법이 발전하면서 컴파일러가 자동 생성해 주는 코드가 많아졌습니다. 그런데, 가만 보면 이런 것에도 패턴이 있는 것 같습니다. 가령, CachedAnonymousMethodDelegate라는 유형이 있는데요.

SynthesizedLocalKind
; http://source.roslyn.io/#Microsoft.CodeAnalysis/SynthesizedLocalKind.cs,c465228f29a95c51,references

/// 
/// Local variable used to cache a delegate that is used in inner block (possibly a loop), 
/// and can be reused for all iterations of the loop.
/// 
CachedAnonymousMethodDelegate = 31,

CachedAnonymousMethodDelegate 유형의 로컬 변수를 생성하려면 다음과 같이 예제 구성을 하면 됩니다.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            DoMethod();
        }

        private static void DoMethod()
        {
            Func<string, bool> func3 = (arg) =>
            {
                return true;
            };

            List<string> list = new List<string>();
            var list2 = list.Where(func3);
        }
    }
}

Visual Studio 2013에서 위의 소스 코드를 컴파일하고 .NET Reflector에서 "C# - None" 옵션으로 보면 다음과 같이 DoMethod 내부에 코딩한 람다 함수가 "CS$<>9__CachedAnonymousMethodDelegate1" 이름의 멤버 필드로 Program 클래스에 정의되면서 캐시 역할의 변수를 합니다. 또한 람다 함수의 코드는 "<DoMethod>b__0"라는 멤버 메서드로 자동 생성되고!

internal class Program
{
    // Fields
    [CompilerGenerated]
    private static Func<string, bool> CS$<>9__CachedAnonymousMethodDelegate1;

    // Methods
    public Program()
    {
        base..ctor();
        return;
    }

    [CompilerGenerated]
    private static bool <DoMethod>b__0(string arg)
    {
        bool flag;
        flag = 1;
    Label_0005:
        return flag;
    }

    private static void DoMethod()
    {
        Func<string, bool> func;
        List<string> list;
        IEnumerable<string> enumerable;
        if (CS$<>9__CachedAnonymousMethodDelegate1 != null)
        {
            goto Label_001B;
        }
        CS$<>9__CachedAnonymousMethodDelegate1 = new Func<string, bool>(null, <DoMethod>b__0);
    Label_001B:
        func = CS$<>9__CachedAnonymousMethodDelegate1;
        list = new List<string>();
        enumerable = Enumerable.Where<string>(list, func);
        return;
    }

    private static void Main(string[] args)
    {
        DoMethod();
        return;
    }
}

재미있는 것은, cache 변수의 역할을 하는 멤버 필드의 이름에 SynthesizedLocalKind::CachedAnonymousMethodDelegate 상숫값의 이름이 반영되어 있다는 것입니다. 게다가 CS$...에 붙는 번호들 같은 경우에도 그냥 붙는 것이 아니라고 합니다. 이에 대해서는 아래의 글을 (재미 삼아) 보시면 될 것 같습니다. ^^

Where to learn about VS debugger 'magic names'
; http://stackoverflow.com/questions/2508828/where-to-learn-about-vs-debugger-magic-names

그런데 역시나 이런 내부적인 규칙들은 public이 아니라는 점에 주의해야 합니다. 실제로 Visual Studio 2015에서 위의 소스 코드를 빌드하면 다음과 같이 전혀 다른 결과를 얻게 됩니다.

internal class Program
{
    // Methods
    public Program()
    {
        base..ctor();
        return;
    }

    private static void DoMethod()
    {
        Func<string, bool> func;
        List<string> list;
        IEnumerable<string> enumerable;
    Label_0020:
        func = <>c.<>9__1_0 ?? (<>c.<>9__1_0 = new Func<string, bool>(<>c.<>9, this.<DoMethod>b__1_0));
        list = new List<string>();
        enumerable = Enumerable.Where<string>(list, func);
        return;
    }

    private static void Main(string[] args)
    {
        DoMethod();
        return;
    }

    [Serializable, CompilerGenerated]
    private sealed class <>c
    {
        // Fields
        public static readonly Program.<>c <>9;
        public static Func<string, bool> <>9__1_0;

        // Methods
        static <>c()
        {
            <>9 = new Program.<>c();
            return;
        }

        public <>c()
        {
            base..ctor();
            return;
        }

        internal bool <DoMethod>b__1_0(string arg)
        {
            bool flag;
            flag = 1;
        Label_0005:
            return flag;
        }
    }
}

즉, CachedAnonymousMethodDelegate 접미사가 붙은 멤버 필드 대신 별도의 임시 클래스(<>c)가 만들어지고 그 안에 필드와 메서드의 본체가 정의됩니다.

이런 차이가 있기 때문에 람다 함수 안에서 다음과 같은 타입 의존적인 코드를 하게 되면,

class Program
{
    static void Main(string[] args)
    {
        Program pg = new Program();
        pg.DoMethod();
    }

    private void DoMethod()
    {
        Func<string, bool> func3 = (arg) =>
        {
            StackFrame st = new StackFrame();

            Console.WriteLine(st.GetMethod().DeclaringType.Name);
            Console.WriteLine(st.GetMethod().DeclaringType.FullName);
            return true;
        };

        List<string> list = new List<string>();
        list.Add("TEST");
        var list2 = list.Where(func3);
        list2.ToList();
    }
}

Visual Studio 2013에서는 다음과 같이 출력이 되고,

Type.Name: Program
Type.FullName: ConsoleApp1.Program 

Visual Studio 2015 이후로는 이런 결과가 나옵니다.

Type.Name: <>c
Type.FullName: ConsoleApp1.Program+<>c

재미있는 것은, Visual Studio 2013에서도 람다 함수 내에 변수를 capture 하게 되면,

public string DoMethod()
{
    StringBuilder sb = new StringBuilder();

    Func<string, bool> func3 = (arg) =>
    {
        sb.AppendLine(arg);
        return true;
    };

    List<string> list = new List<string>();
    list.Add("TEST");
    var list2 = list.Where(func3);
    list2.ToList();
}

2015에서와 같은 결과가 나옵니다.

Visual Studio 2013
Type.Name: <>c
Type.FullName: ConsoleApp1.Program+<>c




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







[최초 등록일: ]
[최종 수정일: 3/31/2017]

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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  38  39  40  [41]  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12592정성태4/10/20219086개발 환경 구성: 566. Docker Desktop for Windows - k8s dashboard의 Kubeconfig 로그인 및 Skip 방법
12591정성태4/9/202112293.NET Framework: 1034. C# - byte 배열을 Hex(16진수) 문자열로 고속 변환하는 방법 [2]파일 다운로드1
12590정성태4/9/20218868.NET Framework: 1033. C# - .NET 4.0 이하에서 Console.IsInputRedirected 구현 [1]
12589정성태4/8/202110170.NET Framework: 1032. C# - Environment.OSVersion의 문제점 및 윈도우 운영체제의 버전을 구하는 다양한 방법 [1]
12588정성태4/7/202110712개발 환경 구성: 565. PowerShell - New-SelfSignedCertificate를 사용해 CA 인증서 생성 및 인증서 서명 방법
12587정성태4/6/202111305개발 환경 구성: 564. Windows 10 - ClickOnce 배포처럼 사용할 수 있는 MSIX 설치 파일 [1]
12586정성태4/5/20219195오류 유형: 710. Windows - Restart-Computer / shutdown 명령어 수행 시 Access is denied(E_ACCESSDENIED)
12585정성태4/5/20218951개발 환경 구성: 563. 기본 생성된 kubeconfig 파일의 내용을 새롭게 생성한 인증서로 구성하는 방법
12584정성태4/1/20219663개발 환경 구성: 562. kubeconfig 파일 없이 kubectl 옵션만으로 실행하는 방법
12583정성태3/29/202111193개발 환경 구성: 561. kubectl 수행 시 다른 k8s 클러스터로 접속하는 방법
12582정성태3/29/20219852오류 유형: 709. Visual C++ - 컴파일 에러 error C2059: syntax error: '__stdcall'
12581정성태3/28/20219786.NET Framework: 1031. WinForm/WPF에서 Console 창을 띄워 출력하는 방법 (2) - Output 디버깅 출력을 AllocConsole로 우회 [2]
12580정성태3/28/20218581오류 유형: 708. SQL Server Management Studio - Execution Timeout Expired.
12579정성태3/28/20218594오류 유형: 707. 중첩 가상화(Nested Virtualization) - The virtual machine could not be started because this platform does not support nested virtualization.
12578정성태3/27/20218918개발 환경 구성: 560. Docker Desktop for Windows 기반의 Kubernetes 구성 (2) - WSL 2 인스턴스에 kind가 구성한 k8s 서비스 위치
12577정성태3/26/202110957개발 환경 구성: 559. Docker Desktop for Windows 기반의 Kubernetes 구성 - WSL 2 인스턴스에 kind 도구로 k8s 클러스터 구성
12576정성태3/25/20218753개발 환경 구성: 558. Docker Desktop for Windows에서 DockerDesktopVM 기반의 Kubernetes 구성 (2) - k8s 서비스 위치
12575정성태3/24/20217896개발 환경 구성: 557. Docker Desktop for Windows에서 DockerDesktopVM 기반의 Kubernetes 구성
12574정성태3/23/202111758.NET Framework: 1030. C# Socket의 Close/Shutdown 동작 (동기 모드)
12573정성태3/22/20219640개발 환경 구성: 556. WSL 인스턴스 초기 설정 명령어 [1]
12572정성태3/22/20219174.NET Framework: 1029. C# - GC 호출로 인한 메모리 압축(Compaction)을 확인하는 방법파일 다운로드1
12571정성태3/21/20218338오류 유형: 706. WSL 2 기반으로 "Enable Kubernetes" 활성화 시 초기화 실패 [1]
12570정성태3/19/202112655개발 환경 구성: 555. openssl - CA로부터 인증받은 새로운 인증서를 생성하는 방법
12569정성태3/18/202111529개발 환경 구성: 554. WSL 인스턴스 export/import 방법 및 단축 아이콘 설정 방법
12568정성태3/18/20217249오류 유형: 705. C# 빌드 - Couldn't process file ... due to its being in the Internet or Restricted zone or having the mark of the web on the file.
12567정성태3/17/20218566개발 환경 구성: 553. Docker Desktop for Windows를 위한 k8s 대시보드 활성화 [1]
... 31  32  33  34  35  36  37  38  39  40  [41]  42  43  44  45  ...