Microsoft MVP성태의 닷넷 이야기
.NET Framework: 823. (번역글) .NET Internals Cookbook Part 8 - C# gotchas [링크 복사], [링크+제목 복사]
조회: 13846
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 11개 있습니다.)

(번역글) .NET Internals Cookbook Part 8 - C# gotchas

이번에도 .NET Internals Cookbook 시리즈의 8번째 글을 번역한 것입니다.

(번역글) .NET Internals Cookbook Part 1 - Exceptions, filters and corrupted processes
; https://www.sysnet.pe.kr/2/0/11838

(번역글) .NET Internals Cookbook Part 2 - GC-related things
; https://www.sysnet.pe.kr/2/0/11869

(번역글) .NET Internals Cookbook Part 3 - Initialization tricks
; https://www.sysnet.pe.kr/2/0/11871

(번역글) .NET Internals Cookbook Part 4 - Type members
; https://www.sysnet.pe.kr/2/0/11872

(번역글) .NET Internals Cookbook Part 5 - Methods, parameters, modifiers
; https://www.sysnet.pe.kr/2/0/11873

(번역글) .NET Internals Cookbook Part 6 - Object internals
; https://www.sysnet.pe.kr/2/0/11874

(번역글) .NET Internals Cookbook Part 7 - Word tearing, locking and others
; https://www.sysnet.pe.kr/2/0/11876

.NET Internals Cookbook Part 8 - C# gotchas
; https://blog.adamfurmanek.pl/2019/04/06/net-internals-cookbook-part-8/

(번역글) .NET Internals Cookbook Part 9 - Finalizers, queues, card tables and other GC stuff
; https://www.sysnet.pe.kr/2/0/11878

(번역글) .NET Internals Cookbook Part 10 - Threads, Tasks, asynchronous code and others
; https://www.sysnet.pe.kr/2/0/11879

(번역글) .NET Internals Cookbook Part 11 - Various C# riddles
; https://www.sysnet.pe.kr/2/0/11882

(번역글) .NET Internals Cookbook Part 12 - Memory structure, attributes, handles
; https://www.sysnet.pe.kr/2/0/11891





52. class와 interface 내에 자식 class/interface를 정의할 수 있을까?

해보면 알죠? ^^

using System;
using System.Threading;

namespace Program
{
    public class Program
    {
        public static void Main(string[] args)
        {
        }
    }
}

class A
{
    class ClassInAClass
    {
    }
}

interface B
{
    // 컴파일 에러
    // error CS0524: 'B.ClassInAnInterface': interfaces cannot declare types
    class ClassInAnInterface
    {
    }
}

class C
{
    interface InterfaceInAClass
    {
    }
}

interface D
{
    // 컴파일 에러
    // error CS0524: 'D.InterfaceInAnInterface': interfaces cannot declare types
    interface InterfaceInAnInterface
    {
    }
}

보는 바와 같이 interface 내에는 class/interface에 상관없이 포함할 수 없습니다. 이에 대해 ECMA 표준에 제출된 문서를 언급하며 interface가 다음과 같이 정의되었다고 합니다.

a named group of methods, locations, and other contracts that shall be implemented by any object type that supports the interface contract of the same name.


즉, interface는 실제 타입은 아니며 타입이 제공하는 메서드들에 이름 지어진 설명자에 불과하다고 합니다. 실제로 다음의 코드에서 Baz 타입은,

using System;

public class Program
{
    public static void Main(string[] args)
    {
        IFoo foo = new Baz();
        foo.Method();
    }
}

interface IFoo
{
    void Method();
}

class Bar
{
    public void Method()
    {
        Console.WriteLine("Bar!");
    }
}

class Baz : Bar, IFoo
{
}

IFoo를 상속하지만 정작 IFoo가 정의한 메서드는 구현하지 않음에도 IFoo 인터페이스로의 형변환과 함께 동작에는 아무런 문제가 없습니다.

심지어, IFoo의 메서드를 담고 있는 Bar::Method는 위와 같이 하나의 어셈블리에 Bar/Baz가 포함되어 컴파일이 되면 Bar::Method를 virtual final 메서드로 컴파일합니다.

.class private auto ansi beforefieldinit Bar
    extends [mscorlib]System.Object
{
    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
    }

    // IFoo를 구현하지도 않았고, Bar::Method에 virtual을 지정하지도 않았지만!
    .method public hidebysig newslot virtual final instance void Method() cil managed
    {
    }
}

.class private auto ansi beforefieldinit Baz
    extends Bar
    implements IFoo
{
    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
    }
}

반면 Bar와 Baz가 다른 어셈블리에 정의되었다면 Bar::Method는 그대로 일반 메서드로 컴파일이 되지만, Baz에는 IFoo.Method가 virtual final로 포함이 됩니다.

// A 어셈블리
.class public auto ansi beforefieldinit Bar
    extends [System.Runtime]System.Object
{
    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
    }

    .method public hidebysig instance void Method() cil managed
    {
    }
}

// A 어셈블리를 참조한 B 어셈블리
.class private auto ansi beforefieldinit Baz
    extends [ClassLibrary1]Bar
    implements [ClassLibrary1]IFoo
{
    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
    }

    .method private hidebysig newslot virtual final instance void IFoo.Method() cil managed
    {
        .override [ClassLibrary1]IFoo::Method
    }
}





53. switch는 어떻게 컴파일이 될까?

컴파일러 버전, 변수 형식, label의 수에 따라 다릅니다. 일례로 다음의 코드를 .NET 4.5, C# 7 컴파일러로 빌드하면,

static int SwitchAsIfElse(int x)
{
    switch (x)
    {
        case 1:
            return 1;
        case 2:
            return 2;
        default:
            return -1;
    }
}

이렇게 if 문의 조합으로 번역이 됩니다.

private static int SwitchAsIfElse(int x)
{
    int result;
    if (x != 1)
    {
        if (x != 2)
        {
            result = -1;
        }
        else
        {
            result = 2;
        }
    }
    else
    {
        result = 1;
    }
    return result;
}

반면 다음의 코드는,

static int SwitchAsSwitch(int x)
{
    switch (x)
    {
        case 1:
            return 1;
        case 2:
            return 2;
        case 3:
            return 3;
        case 4:
            return 4;
        case 5:
            return 5;
        case 6:
            return 6;
        default:
            return -1;
    }
}

그대로 switch 구문으로 번역됩니다.

private static int SwitchAsSwitch(int x)
{
    int result;
    switch (x)
    {
    case 1:
        result = 1;
        break;
    case 2:
        result = 2;
        break;
    case 3:
        result = 3;
        break;
    case 4:
        result = 4;
        break;
    case 5:
        result = 5;
        break;
    case 6:
        result = 6;
        break;
    default:
        result = -1;
        break;
    }
    return result;
}

문자열 상수의 경우에는,

static void SwitchAsIfElse(string x)
{
    switch (x)
    {
        case "1":
            break;
        case "2":
            break;
        case "3":
            break;
        case "4":
            break;
        case "5":
            break;
        case "6":
            break;
    }
}

단순 if 문의 조합으로 번역되기도 하지만,

private static void SwitchAsIfElse(string x)
{
	if (!(x == "1"))
	{
		if (!(x == "2"))
		{
			if (!(x == "3"))
			{
				if (!(x == "4"))
				{
					if (!(x == "5"))
					{
						if (!(x == "6"))
						{
						}
					}
				}
			}
		}
	}
}

다음과 같이 레이블이 늘어나면,

static void SwitchWithHashes(string x)
{
    switch (x)
    {
        case "1":
            break;
        case "2":
            break;
        case "3":
            break;
        case "4":
            break;
        case "5":
            break;
        case "6":
            break;
        case "7":
            break;
    }
}

속도를 높이기 위해 해시코드 연산이 동반됩니다.

private static void SwitchWithHashes(string x)
{
    uint num = <PrivateImplementationDetails>.ComputeStringHash(x);
    if (num <= 839689206u)
    {
        if (num != 806133968u)
        {
            if (num != 822911587u)
            {
                if (num == 839689206u)
                {
                    if (!(x == "7"))
                    {
                    }
                }
            }
            else
            {
                if (!(x == "4"))
                {
                }
            }
        }
        else
        {
            if (!(x == "5"))
            {
            }
        }
    }
    else
    {
        if (num <= 873244444u)
        {
            if (num != 856466825u)
            {
                if (num == 873244444u)
                {
                    if (!(x == "1"))
                    {
                    }
                }
            }
            else
            {
                if (!(x == "6"))
                {
                }
            }
        }
        else
        {
            if (num != 906799682u)
            {
                if (num == 923577301u)
                {
                    if (!(x == "2"))
                    {
                    }
                }
            }
            else
            {
                if (!(x == "3"))
                {
                }
            }
        }
    }
}





54. __makeref, __refvalue, __reftype, __arglist

처음 3개의 예약어(__makeref, __refvalue, __reftype)에 대해서는 다음의 글을 참고하시고,

Custom memory allocation in C# Part 1 - Allocating object on a stack
; https://blog.adamfurmanek.pl/2016/04/23/custom-memory-allocation-in-c-part-1/

__arglist 사용 예는 이렇습니다.

using System;
using System.Threading;

namespace Program
{
    public class Program
    {
        public static void Main(string[] args)
        {
            ShowArgList(__arglist(5, 6.0, "abc", new object()));
        }

        public static void ShowArgList(__arglist)
        {
            Console.WriteLine("ShowArgList");
            ArgIterator ai = new ArgIterator(__arglist);
            while (ai.GetRemainingCount() > 0)
            {
                TypedReference tr = ai.GetNextArg();
                Console.WriteLine(TypedReference.ToObject(tr));
            }
        }
    }
}

이때 ShowArgList를 호출하는 IL 코드는 "vararg"와 "..."가 사용됩니다.

IL_0015: call vararg void Program.Program::ShowArgList(...,
                                                        int32,
                                                        float64,
                                                        string,
                                                        object)

참고로, 저도 예전에 __makeref, __refvalue는 다음의 글에서 다룬 적이 있습니다.

C#에서 enum을 boxing 없이 int로 변환하기 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/11506

(Unity가 사용하는) 모노 런타임의 __makeref 오류
; https://www.sysnet.pe.kr/2/0/11564





55. C/C++의 union을 C#으로 표현하는 방법

LayoutKind를 Explicit로 하고 FieldOffset을 같게 만드는 방법으로 union을 표현할 수 있습니다. 다음은 이에 대한 예제입니다.

using System;
using System.Threading;
using System.Runtime.InteropServices;

public class Program
{
    public static void Main(string[] args)
    {
        var array = new ByteArray();
        array.Int = 0xBADF00D;
        Console.WriteLine(array.Int);
        Console.WriteLine(array.Byte1.ToString("X"));
        Console.WriteLine(array.Byte2.ToString("X"));
        Console.WriteLine(array.Byte3.ToString("X"));
        Console.WriteLine(array.Byte4.ToString("X"));
    }
}

[StructLayout(LayoutKind.Explicit)]
struct ByteArray
{
    [FieldOffset(0)]
    public byte Byte1;
    [FieldOffset(1)]
    public byte Byte2;
    [FieldOffset(2)]
    public byte Byte3;
    [FieldOffset(3)]
    public byte Byte4;
    [FieldOffset(0)]
    public int Int;
}

/* 출력 결과
195948557
D
F0
AD
B
*/





56. x == x 평가가 false로 나오는 경우와 이럴 때 x.Equals(x)로 비교한다면?

다음의 코드를 보면,

using System;
using System.Threading;

namespace Program
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // 컴파일 경고
            // warning CS1718: Comparison made to same variable; did you mean to compare something else?
            Console.WriteLine(Double.NaN == Double.NaN);

            Console.WriteLine(Double.NaN.Equals(Double.NaN));
        }
    }
}

/* 출력 결과
False
True
*/

x == x 평가가 False로 나옵니다. 어찌 보면 이상할 수 있는데 IEEE 754 표준에 "NaN"은 자신과 비교할 수 없다고 명시되었다고 합니다. 그래서 이건 꼭 C#만의 코드 결과가 아니라 다른 언어에서도 마찬가지의 결과를 볼 수 있습니다.

그러면서도 Equals 연산자는 NaN까지도 비교할 수 있게 만들어진 것입니다.

Equals 메서드와 == 연산자의 차이점
; https://www.sysnet.pe.kr/2/0/11872#tag24





57. C#에서 (타입에 소속되지 않은) 전역 변수를 가질 수 있을까?

C# 문법으로는 안 되지만, IL 코드로는 가능합니다.

// Metadata version: v4.0.30319
.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 4:0:0:0
}
.assembly ConsoleApp1
{
// ...[생략]...
  .hash algorithm 0x00008004
  .ver 1:0:0:0
}
.module ConsoleApp1.exe
// MVID: {DBF8C2F8-6FC2-4C37-9E70-F78CE357CCE8}
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003       // WINDOWS_CUI
.corflags 0x00020003    //  ILONLY 32BITPREFERRED
// Image base: 0x02B90000

.field static int32 X

.class private auto ansi Program
       extends [mscorlib]System.Object
{
  .method private hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // Code size       8 (0x8)
    .maxstack  1
    .locals init ([0] class Program pg)
    IL_0000:  nop
    IL_0001:  newobj     instance void Program::.ctor()
    IL_0006:  stloc.0
            ldsfld     int32 X
            call       void [mscorlib]System.Console::WriteLine(int32)
    IL_0007:  ret
  } // end of method Program::Main

  .method private hidebysig specialname rtspecialname static 
          void  .cctor() cil managed
  {
    // Code size       9 (0x9)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldc.i4.2
              stsfld     int32 X
    IL_0007:  nop
    IL_0008:  ret
  } // end of method Program::.cctor

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       8 (0x8)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  nop
    IL_0007:  ret
  } // end of method Program::.ctor

} // end of class Program

필드를 정의하는 방법과 get/set하는 코드에 어떠한 타입도 붙지 않은 것을 볼 수 있습니다.

[필드 정의]
.field static int32 X

[get 접근]
ldsfld     int32 X

[set 접근]
stsfld     int32 X





58. try/catch/finally 절에서 yield/async를 할 수 있을까?

yield는 사용할 수 없지만 async 코드는 (C# 6.0부터) 호출할 수 있습니다.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Program
{
    public class Program
    {
        public static void Main(string[] args)
        {
        }

        static IEnumerable<int> YieldWithTryCatchFinally()
        {
            yield return 1;
            try
            {
                // error CS1626: Cannot yield a value in the body of a try block with a catch clause
                // yield return 2;
            }
            catch
            {
                // error CS1631: Cannot yield a value in the body of a catch clause
                // yield return 3;
            }
            finally
            {
                // error CS1625: Cannot yield in the body of a finally clause
                // yield return 4;
            }
        }

        static IEnumerable<int> YieldWithTryFinally()
        {
            yield return 1;
            try
            {
                yield return 2;
            }
            finally
            {
                // error CS1625: Cannot yield in the body of a finally clause
                // yield return 3;
            }
        }

        static async Task AwaitWithTryCatchFinally()
        {
            await Task.Yield();
            try
            {
                await Task.Yield();
            }
            catch
            {
                await Task.Yield();
            }
            finally
            {
                await Task.Yield();
            }
        }
    }
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)



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

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/17/2021]

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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  [27]  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
12945정성태1/28/20226263오류 유형: 791. SQL 서버 로그인 시 localhost는 되고, 127.0.0.1로는 안 되는 문제
12944정성태1/28/20228622.NET Framework: 1143. C# - Entity Framework Core 6 개요
12943정성태1/27/20227538.NET Framework: 1142. .NET 5+로 포팅 시 플랫폼 호환성 경고 메시지(SYSLIB0006, SYSLIB0011, CA1416)파일 다운로드1
12942정성태1/27/20227808.NET Framework: 1141. XmlSerializer와 Dictionary 타입파일 다운로드1
12941정성태1/26/20229215오류 유형: 790. AKS/k8s - pod 상태가 Pending으로 지속되는 경우
12940정성태1/26/20226635오류 유형: 789. AKS에서 hpa에 따른 autoscale 기능이 동작하지 않는다면?
12939정성태1/25/20227310.NET Framework: 1140. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 MP3 오디오 파일 인코딩/디코딩하는 예제파일 다운로드1
12938정성태1/24/20229583개발 환경 구성: 633. Docker Desktop + k8s 환경에서 local 이미지를 사용하는 방법
12937정성태1/24/20227420.NET Framework: 1139. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 오디오(mp2) 인코딩하는 예제(encode_audio.c) [2]파일 다운로드1
12936정성태1/22/20227380.NET Framework: 1138. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 멀티미디어 파일의 메타데이터를 보여주는 예제(metadata.c)파일 다운로드1
12935정성태1/22/20227555.NET Framework: 1137. ffmpeg의 파일 해시 예제(ffhash.c)를 C#으로 포팅파일 다운로드1
12934정성태1/22/20227109오류 유형: 788. Warning C6262 Function uses '65564' bytes of stack: exceeds /analyze:stacksize '16384'. Consider moving some data to heap. [2]
12933정성태1/21/20227665.NET Framework: 1136. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 MP2 오디오 파일 디코딩 예제(decode_audio.c)파일 다운로드1
12932정성태1/20/20228114.NET Framework: 1135. C# - ffmpeg(FFmpeg.AutoGen)로 하드웨어 가속기를 이용한 비디오 디코딩 예제(hw_decode.c) [2]파일 다운로드1
12931정성태1/20/20226283개발 환경 구성: 632. ASP.NET Core 프로젝트를 AKS/k8s에 올리는 과정
12930정성태1/19/20226883개발 환경 구성: 631. AKS/k8s의 Volume에 파일 복사하는 방법
12929정성태1/19/20226667개발 환경 구성: 630. AKS/k8s의 Pod에 Volume 연결하는 방법
12928정성태1/18/20226813개발 환경 구성: 629. AKS/Kubernetes에서 호스팅 중인 pod에 shell(/bin/bash)로 진입하는 방법
12927정성태1/18/20226552개발 환경 구성: 628. AKS 환경에 응용 프로그램 배포 방법
12926정성태1/17/20227032오류 유형: 787. AKS - pod 배포 시 ErrImagePull/ImagePullBackOff 오류
12925정성태1/17/20227151개발 환경 구성: 627. AKS의 준비 단계 - ACR(Azure Container Registry)에 docker 이미지 배포
12924정성태1/15/20228616.NET Framework: 1134. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) [2]파일 다운로드1
12923정성태1/15/20227582개발 환경 구성: 626. ffmpeg.exe를 사용해 비디오 파일을 MPEG1 포맷으로 변경하는 방법
12922정성태1/14/20226633개발 환경 구성: 625. AKS - Azure Kubernetes Service 생성 및 SLO/SLA 변경 방법
12921정성태1/14/20225625개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/20226394오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
... 16  17  18  19  20  21  22  23  24  25  26  [27]  28  29  30  ...