Microsoft MVP성태의 닷넷 이야기
.NET Framework: 823. (번역글) .NET Internals Cookbook Part 8 - C# gotchas [링크 복사], [링크+제목 복사]
조회: 13848
글쓴 사람
정성태 (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)
13020정성태3/30/20226420.NET Framework: 1187. RDP 접속 시 WPF UserControl의 Unloaded 이벤트 발생파일 다운로드1
13019정성태3/30/20226399.NET Framework: 1186. Win32 Message를 Code로부터 메시지 이름 자체를 구하고 싶다면?파일 다운로드1
13018정성태3/29/20226928.NET Framework: 1185. C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요? [5]
13017정성태3/28/20226774.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기 [3]
13016정성태3/27/20227614.NET Framework: 1183. C# 11에 추가된 ref 필드의 (우회) 구현 방법파일 다운로드1
13015정성태3/26/20228961.NET Framework: 1182. C# 11 - ref struct에 ref 필드를 허용 [1]
13014정성태3/23/20227573VC++: 155. CComPtr/CComQIPtr과 Conformance mode 옵션의 충돌 [1]
13013정성태3/22/20225887개발 환경 구성: 641. WSL 우분투 인스턴스에 파이썬 2.7 개발 환경 구성하는 방법
13012정성태3/21/20225231오류 유형: 803. C# - Local '...' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
13011정성태3/21/20226690오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225651오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
13009정성태3/20/20227195개발 환경 구성: 640. docker - ibmcom/db2 컨테이너 실행
13008정성태3/19/20226480VS.NET IDE: 176. 비주얼 스튜디오 - 솔루션 탐색기에서 프로젝트를 선택할 때 csproj 파일이 열리지 않도록 만드는 방법
13007정성태3/18/20226149.NET Framework: 1181. C# - Oracle.ManagedDataAccess의 Pool 및 그것의 연결 개체 수를 알아내는 방법파일 다운로드1
13006정성태3/17/20227178.NET Framework: 1180. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 remuxing.c 예제 포팅
13005정성태3/17/20226062오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
13004정성태3/16/20226089디버깅 기술: 182. windbg - 닷넷 메모리 덤프에서 AppDomain에 걸친 정적(static) 필드 값을 조사하는 방법
13003정성태3/15/20226232.NET Framework: 1179. C# - (.NET Framework를 위한) Oracle.ManagedDataAccess 패키지의 성능 카운터 설정 방법
13002정성태3/14/20226982.NET Framework: 1178. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 http_multiclient.c 예제 포팅
13001정성태3/13/20227388.NET Framework: 1177. C# - 닷넷에서 허용하는 메서드의 매개변수와 호출 인자의 최대 수
13000정성태3/12/20226948.NET Framework: 1176. C# - Oracle.ManagedDataAccess.Core의 성능 카운터 설정 방법
12999정성태3/10/20226442.NET Framework: 1175. Visual Studio - 프로젝트 또는 솔루션의 Clean 작업 시 응용 프로그램에서 생성한 파일을 함께 삭제파일 다운로드1
12998정성태3/10/20226059.NET Framework: 1174. C# - ELEMENT_TYPE_FNPTR 유형의 사용 예
12997정성태3/10/202210439오류 유형: 799. Oracle.ManagedDataAccess - "ORA-01882: timezone region not found" 오류가 발생하는 이유
12996정성태3/9/202215599VS.NET IDE: 175. Visual Studio - 인텔리센스에서 오버로드 메서드를 키보드로 선택하는 방법
12995정성태3/8/20227893.NET Framework: 1173. .NET에서 Producer/Consumer를 구현한 BlockingCollection<T>
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...