Microsoft MVP성태의 닷넷 이야기
.NET Framework: 823. (번역글) .NET Internals Cookbook Part 8 - C# gotchas [링크 복사], [링크+제목 복사]
조회: 13851
글쓴 사람
정성태 (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)
13221정성태1/19/20234163Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234314오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20233872Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233795VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234391디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234653디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236159Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235729.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235269오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235028기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235112웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234132Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234029Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20233963.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224270.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
13206정성태12/24/20224474.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [3]파일 다운로드1
13205정성태12/24/20224871.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)파일 다운로드1
13204정성태12/22/20224152.NET Framework: 2082. C# - (LSA_UNICODE_STRING 예제로) CustomMarshaler 사용법파일 다운로드1
13203정성태12/22/20224286.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/20224662기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
13201정성태12/20/20225286오류 유형: 835. PyCharm 사용 시 C 드라이브 용량 부족
13200정성태12/19/20224161오류 유형: 834. 이벤트 로그 - SSL Certificate Settings created by an admin process for endpoint
13199정성태12/19/20224449개발 환경 구성: 656. Internal Network 유형의 스위치로 공유한 Hyper-V의 VM과 호스트가 통신이 안 되는 경우
13198정성태12/18/20224325.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?파일 다운로드1
13197정성태12/17/20224267.NET Framework: 2079. .NET Core/5+ 환경에서 XmlSerializer 사용 시 System.IO.FileNotFoundException 예외 발생하는 경우파일 다운로드1
13196정성태12/16/20224397.NET Framework: 2078. .NET Core/5+를 위한 SGen(Microsoft.XmlSerializer.Generator) 사용법
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...