Microsoft MVP성태의 닷넷 이야기
.NET Framework: 823. (번역글) .NET Internals Cookbook Part 8 - C# gotchas [링크 복사], [링크+제목 복사]
조회: 13835
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 31  32  [33]  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12793정성태8/20/20219034.NET Framework: 1097. C# 10 - (3) 개선된 변수 초기화 판정파일 다운로드1
12792정성태8/19/20219463.NET Framework: 1096. C# 10 - (2) 전역 네임스페이스 선언파일 다운로드1
12791정성태8/19/20217855.NET Framework: 1095. C# COM 개체를 C++에서 사용하는 예제 [3]파일 다운로드1
12790정성태8/18/202110076.NET Framework: 1094. C# 10 - (1) 구조체를 생성하는 record struct파일 다운로드1
12789정성태8/18/20219083개발 환경 구성: 597. PyCharm - 윈도우 환경에서 WSL을 이용해 파이썬 앱 개발/디버깅하는 방법
12788정성태8/17/20217675.NET Framework: 1093. C# - 인터페이스의 메서드가 다형성을 제공할까요? (virtual일까요?)파일 다운로드1
12787정성태8/17/20217862.NET Framework: 1092. (책 내용 수정) "4.5.1.4 인터페이스"의 "인터페이스와 다형성"
12786정성태8/16/20219373.NET Framework: 1091. C# - Python range 함수 구현 (2) INumber<T>를 이용한 개선 [1]파일 다운로드1
12785정성태8/16/20217620.NET Framework: 1090. .NET 6 Preview 7에 추가된 숫자 형식에 대한 제네릭 연산 지원 [1]파일 다운로드1
12784정성태8/15/20217008오류 유형: 757. 구글 메일 - 아웃룩에서 메일 전송 시 Sending' reported error (0x800CCC0F, 0x800CCC92)
12783정성태8/15/20216638.NET Framework: 1089. C# - Indexer에 Range 및 람다 식을 이용한 필터 구현 [1]파일 다운로드1
12782정성태8/14/20216438오류 유형: 756. 파이썬 - 윈도우 환경에서 pytagcloud의 한글 출력 방법
12781정성태8/14/20218569오류 유형: 755. 파이썬 - konlpy 사용 시 JVM과 jpype1 관련 오류
12780정성태8/13/20216964.NET Framework: 1088. C# - 버스 노선 및 위치 정보 조회 API 사용을 위한 기초 라이브러리 [2]
12779정성태8/13/20218776개발 환경 구성: 596. 공공 데이터 포털에서 버스 노선 및 위치 정보 조회 API 사용법
12778정성태8/12/20216126오류 유형: 755. PyCharm - "Manage Repositories"의 목록이 나오지 않는 문제
12777정성태8/12/20217785오류 유형: 754. Visual Studio - Input or output cannot be redirected because the specified file is invalid.
12776정성태8/12/20217082오류 유형: 753. gunicorn과 uwsgi 함께 사용 시 ERR_CONNECTION_REFUSED
12775정성태8/12/202117032스크립트: 22. 파이썬 - 윈도우 환경에서 개발한 Django 앱을 WSL 환경의 gunicorn을 이용해 실행
12774정성태8/11/20218656.NET Framework: 1087. C# - Collection 개체의 다중 스레드 접근 시 "Operations that change non-concurrent collections must have exclusive access" 예외 발생
12773정성태8/11/20217809개발 환경 구성: 595. PyCharm - WSL과 연동해 Django App을 윈도우에서 리눅스 대상으로 개발
12772정성태8/11/20219317스크립트: 21. 파이썬 - 윈도우 환경에서 개발한 Django 앱을 WSL 환경의 uwsgi를 이용해 실행 [1]
12771정성태8/11/20217712Windows: 196. "Microsoft Windows Subsystem for Linux Background Host" / "Vmmem"을 종료하는 방법
12770정성태8/11/20218398.NET Framework: 1086. C# - Windows Forms 응용 프로그램의 자식 컨트롤 부하파일 다운로드1
12769정성태8/11/20216397오류 유형: 752. Python - ImportError: No module named pip._internal.cli.main 두 번째 이야기
12768정성태8/10/20217412.NET Framework: 1085. .NET 6에 포함된 신규 BCL API [1]파일 다운로드1
... 31  32  [33]  34  35  36  37  38  39  40  41  42  43  44  45  ...