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 저도 가끔 그러면서 다시 "배웁니다." ^^;
정성태

... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13071정성태6/9/20227231스크립트: 39. Python에서 cx_Oracle 환경 구성
13070정성태6/8/20227045오류 유형: 813. Windows 11에서 입력 포커스가 바뀌는 문제 [1]
13069정성태5/26/20229275.NET Framework: 2019. C# - .NET에서 제공하는 3가지 Timer 비교 [2]
13068정성태5/24/20227734.NET Framework: 2018. C# - 일정 크기를 할당하는 동안 GC를 (가능한) 멈추는 방법 [1]파일 다운로드1
13067정성태5/23/20227099Windows: 206. Outlook - 1년 이상 지난 메일이 기본적으로 안 보이는 문제
13066정성태5/23/20226410Windows: 205. Windows 11 - Windows + S(또는 Q)로 뜨는 작업 표시줄의 검색 바가 동작하지 않는 경우
13065정성태5/20/20227084.NET Framework: 2017. C# - Windows I/O Ring 소개 [2]파일 다운로드1
13064정성태5/18/20226649.NET Framework: 2016. C# - JIT 컴파일러의 인라인 메서드 처리 유무
13063정성태5/18/20227068.NET Framework: 2015. C# - 인라인 메서드(inline methods)
13062정성태5/17/20227857.NET Framework: 2014. C# - async/await 그리고 스레드 (4) 비동기 I/O 재현파일 다운로드1
13061정성태5/16/20226671.NET Framework: 2013. C# - FILE_FLAG_OVERLAPPED가 적용된 파일의 읽기/쓰기 시 Position 관리파일 다운로드1
13060정성태5/15/20229112.NET Framework: 2012. C# - async/await 그리고 스레드 (3) Task.Delay 재현파일 다운로드1
13059정성태5/14/20227606.NET Framework: 2011. C# - CLR ThreadPool의 I/O 스레드에 작업을 맡기는 방법 [1]파일 다운로드1
13058정성태5/13/20227533.NET Framework: 2010. C# - ThreadPool.SetMaxThreads 사용법
13057정성태5/12/20229205오류 유형: 812. 파이썬 - ImportError: cannot import name ...
13056정성태5/12/20226372.NET Framework: 2009. C# - async/await 그리고 스레드 (2) MyTask의 호출 흐름 [2]파일 다운로드1
13055정성태5/11/20229264.NET Framework: 2008. C# - async/await 그리고 스레드 (1) MyTask로 재현 [11]파일 다운로드1
13054정성태5/11/20226787.NET Framework: 2007. C# - 10진수 숫자를 담은 문자열을 숫자로 변환하는 방법 [11]파일 다운로드1
13053정성태5/10/20226420.NET Framework: 2006. C# - GC.KeepAlive 메서드의 역할
13052정성태5/9/20226429.NET Framework: 2005. C# - 생성한 참조 개체가 언제 GC의 정리 대상이 될까요?
13051정성태5/8/20226381.NET Framework: 2004. C# XingAPI - ACF 검색 결과로 구한 CSV 파일을 통해 퀀트 종목 찾기파일 다운로드1
13050정성태5/6/20226398.NET Framework: 2003. C# - COM 개체의 이벤트 핸들러에서 발생하는 예외에 대한 CLR의 특별 대우파일 다운로드1
13049정성태5/6/20225374오류 유형: 811. GoLand - Error: Cannot find package
13048정성태5/6/20226499오류 유형: 810. "ASUS TUF GAMING B550M-PLUS (WI-FI)" 모델에서 블루투스 장치가 인식이 안 되는 문제
13047정성태5/6/20226485오류 유형: 809. Speech Recognition could not start
13046정성태5/5/20226776.NET Framework: 2002. C# XingAPI - ACF 파일을 이용한 퀀트 종목 찾기(t1857)
... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...