Microsoft MVP성태의 닷넷 이야기
.NET Framework: 823. (번역글) .NET Internals Cookbook Part 8 - C# gotchas [링크 복사], [링크+제목 복사]
조회: 13854
글쓴 사람
정성태 (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)
12921정성태1/14/20225626개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/20226395오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
12919정성태1/13/20226224Windows: 199. Host Network Service (HNS)에 의해서 점유되는 포트
12918정성태1/13/20226442Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/20225671오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/20225406오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/20225675오류 유형: 783. Visual Studio - We didn't find any interpreters
12914정성태1/11/20227575VS.NET IDE: 172. 비주얼 스튜디오 2022의 파이선 개발 환경 지원
12913정성태1/11/20228118.NET Framework: 1133. C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법 [1]
12912정성태1/11/20228745개발 환경 구성: 623. ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법 [1]
12911정성태1/11/20226097VS.NET IDE: 171. 비주얼 스튜디오 - 더 이상 만들 수 없는 "ASP.NET Core 3.1 Web Application (.NET Framework)" 프로젝트
12910정성태1/10/20226559제니퍼 .NET: 30. 제니퍼 닷넷 적용 사례 (8) - CPU high와 DB 쿼리 성능에 문제가 함께 있는 사이트
12909정성태1/10/20227959오류 유형: 782. Visual Studio 2022 설치 시 "Couldn't install Microsoft.VisualCpp.Redist.14.Latest"
12908정성태1/10/20225814.NET Framework: 1132. C# - ref/out 매개변수의 IL 코드 처리
12907정성태1/9/20226248오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20226857.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
12905정성태1/8/20226520오류 유형: 780. Could not load file or assembly 'Microsoft.VisualStudio.TextTemplating.VSHost.15.0, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
12904정성태1/8/20228552개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227147.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20227180오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
12901정성태1/5/20227273오류 유형: 778. C# - .NET 5+에서 warning CA1416: This call site is reachable on all platforms. '...' is only supported on: 'windows' 경고 발생
12900정성태1/5/20228921개발 환경 구성: 622. vcpkg로 ffmpeg를 빌드하는 경우 생성될 구성 요소 제어하는 방법
12899정성태1/3/20228405개발 환경 구성: 621. windbg에서 python 스크립트 실행하는 방법 - pykd (2)
12898정성태1/2/20228958.NET Framework: 1129. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제(encode_video.c) [1]파일 다운로드1
12897정성태1/2/20227840.NET Framework: 1128. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 [4]파일 다운로드1
12896정성태1/1/202210709.NET Framework: 1127. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...