반응형
사용자 정의 명시적, 암시적 변환 연산자
- 명시적 변환 연산자 : explicit operator
- 암시적 변환 연산자 : implicit operator
public static implicit operator byte(Digit d) => d.digit;
public static explicit operator Digit(byte b) => new Digit(b);
(C++에는 explicit 키워드가 있는데 해당 키워드를 생성자에 추가하면 암시적인 형변환을 제한한다. 오직 명시적 형변환 만을 허용)
예제 코드
using System;
public readonly struct Digit
{
private readonly byte digit;
public Digit(byte digit)
{
if (digit > 9)
{
throw new ArgumentOutOfRangeException(nameof(digit), "Digit cannot be greater than nine.");
}
this.digit = digit;
}
public static implicit operator byte(Digit d) => d.digit;
public static explicit operator Digit(byte b) => new Digit(b);
public override string ToString() => $"{digit}";
}
public static class UserDefinedConversions
{
public static void Main()
{
var d = new Digit(7);
byte number = d;
Console.WriteLine(number); // output: 7
Digit digit = (Digit)number;
Console.WriteLine(digit); // output: 7
}
}
참조 사이트
사용자 정의 명시적 및 암시적 변환 연산자 - 다양한 형식으로 변환 제공 - C#
C#에서 사용자 지정 암시적 및 명시적 형식 변환을 정의하는 방법을 알아봅니다. 연산자는 개체를 새 형식으로 캐스팅하는 기능을 제공합니다.
learn.microsoft.com
'프로그래밍 > C#' 카테고리의 다른 글
C# IEnumerable, IEnumerator에 대해서 (2) | 2023.10.05 |
---|---|
C# 정수 숫자 형식 (2) | 2023.09.26 |
C# Substring 복습하기 (0) | 2023.09.20 |
C# Math.Sqrt(Double) vs Math.Pow(Double, Double) (8) | 2023.08.28 |
Environment.TickCount (2) | 2023.08.24 |
댓글