Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 5개 있습니다.)
.NET Framework: 673. C#에서 enum을 boxing 없이 int로 변환하기
; https://www.sysnet.pe.kr/2/0/11270

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

.NET Framework: 779. C# 7.3에서 enum을 boxing 없이 int로 변환하기 - 세 번째 이야기
; https://www.sysnet.pe.kr/2/0/11565

.NET Framework: 1042. C# - enum 값을 int로 암시적(implicit) 형변환하는 방법?
; https://www.sysnet.pe.kr/2/0/12606

.NET Framework: 2131. C# - Source Generator로 해결하는 enum 박싱 문제
; https://www.sysnet.pe.kr/2/0/13384




C# - enum 값을 int로 암시적(implicit) 형변환하는 방법?

때로는 enum 값이 int로 암시적 형변환이 있었으면 좋을 때가 있습니다.

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

위의 박싱 문제 말고도 어떤 경우에는 다양한 enum 값을 받아야 할 수도 있는데요, 그럴 때 보통 int로 처리하게 됩니다.

using System;

class Program
{
    static void Main(string[] args)
    {
        PrintEnumValue((int)Project.Debug);
        PrintEnumValue((int)Solution.Project);
    }

    private static void PrintEnumValue(int value)
    {
        Console.WriteLine(value);
    }
}

enum Project
{
    Debug = 1,
    Release = 2,
}

enum Solution
{
    Project = 3,
    Item = 4,
}

보는 바와 같이, 매번 전달할 때 (int) 형변환하는 것이 꽤나 귀찮은 문제입니다. (좀 더 엄밀히 따지면, 이건 귀찮음의 문제가 아니라 개발자라는 직업의 성격상 뭔가,,, 마음속 깊이 받아들여지지 않는 무언가가 있습니다. ^^;)

어쩌면 이에 대한 이상적인 해결책은, 그러니까 기존 문법에 기반을 둬 추가한다면 enum 타입에서도 연산자 재정의를 지원하는 것입니다.

enum Project
{
    Debug = 1,
    Release = 2,

    // 지원하지 않는 문법: 컴파일 오류
    public static implicit operator int(Project value)
    {
        return (int)value;
    }
}

enum Solution
{
    Project = 3,
    Item = 4,

    // 지원하지 않는 문법: 컴파일 오류
    public static implicit operator int(Solution value)
    {
        return (int)value;
    }
}

보다시피, 지원하지 않는다는 것이 문제라서. ^^;




이에 대해 검색해 보면, 그나마 최선의 방법을 다음의 Q&A에서 보게 됩니다.

Can we define implicit conversions of enums in c#?
; https://stackoverflow.com/questions/261663/can-we-define-implicit-conversions-of-enums-in-c

덧글에 보면 중계 타입으로 PrimitiveEnum을 정의하고 있는데요,

McKabue.Extentions.Utility/src/McKabue.Extentions.Utility/Enums/PrimitiveEnum.cs
; https://github.com/McKabue/McKabue.Extentions.Utility/blob/master/src/McKabue.Extentions.Utility/Enums/PrimitiveEnum.cs

using System;
using System.Collections.Generic;
using System.Text;

public class PrimitiveEnum
{
    private Enum _enum;

    public PrimitiveEnum(Enum _enum)
    {
        this._enum = _enum;
    }

    public Enum Enum => _enum;


    public static implicit operator PrimitiveEnum(Enum _enum)
    {
        return new PrimitiveEnum(_enum);
    }

    public static implicit operator Enum(PrimitiveEnum primitiveEnum)
    {
        return primitiveEnum.Enum;
    }

    public static implicit operator byte(PrimitiveEnum primitiveEnum)
    {
        return Convert.ToByte(primitiveEnum.Enum);
    }

    public static implicit operator sbyte(PrimitiveEnum primitiveEnum)
    {
        return Convert.ToSByte(primitiveEnum.Enum);
    }

    public static implicit operator short(PrimitiveEnum primitiveEnum)
    {
        return Convert.ToInt16(primitiveEnum.Enum);
    }

    public static implicit operator ushort(PrimitiveEnum primitiveEnum)
    {
        return Convert.ToUInt16(primitiveEnum.Enum);
    }

    public static implicit operator int(PrimitiveEnum primitiveEnum)
    {
        return Convert.ToInt32(primitiveEnum.Enum);
    }

    public static implicit operator uint(PrimitiveEnum primitiveEnum)
    {
        return Convert.ToUInt32(primitiveEnum.Enum);
    }

    public static implicit operator long(PrimitiveEnum primitiveEnum)
    {
        return Convert.ToInt64(primitiveEnum.Enum);
    }

    public static implicit operator ulong(PrimitiveEnum primitiveEnum)
    {
        return Convert.ToUInt64(primitiveEnum.Enum);
    }
}

이것을 이용하면 enum 타입을 쓰면서도 자연스럽게 int로 형변환하는 것이 가능합니다.

static void Main(string[] args)
{
    PrintEnumValue(Project.Debug);
    PrintEnumValue(Solution.Project);
}

/* 출력 결과
1
Debug
3
Project
*/

private static void PrintEnumValue(PrimitiveEnum value)
{
    int intValue = value; // 암시적 형변환 (박싱 발생)

    Console.WriteLine(intValue); // 출력: 정숫값
    Console.WriteLine(value.Enum); // 출력: enum 문자열
}

/*
private static void PrintEnumValue(Enum value)
{
    int intValue = Convert.ToInt32(value); // (박싱 발생)

    Console.WriteLine(intValue);    // 출력: 정숫값
    Console.WriteLine(value);       // 출력: enum 문자열
}
*/

현재로서는, 이 정도 수준이 최선일 듯합니다.

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/21/2021]

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

비밀번호

댓글 작성자
 



2021-04-23 11시24분
[kernel] 새롭게 올려주신 글 덕분에 4년전 댓글 드렸던 글까지 다시 복기하게 되네요. 좋은 글 올려주셔서 항상 고맙습니다. :D
[guest]
2021-04-23 11시51분
@kernel 저도 가끔 그러면서 다시 "배웁니다." ^^;
정성태

1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...
NoWriterDateCnt.TitleFile(s)
13298정성태3/27/20233682Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234358Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233694Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20233963Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234138.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234205오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234330Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234742.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234248.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233439Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233553Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233709Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234165Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233757Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20233955Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233497오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20233822Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233732Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/20234495개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234048오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/20234018개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/20234661개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/20234338.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20234693.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234277.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20233973.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...