방법: 구조체 간의 사용자 정의 변환 구현(C# 프로그래밍 가이드)
다음은 RomanNumeral
과 BinaryNumeral
의 두 구조체를 정의하고 이 두 구조체 간의 변환을 보여 주는 예제입니다.
예제
struct RomanNumeral
{
private int value;
public RomanNumeral(int value) //constructor
{
this.value = value;
}
static public implicit operator RomanNumeral(int value)
{
return new RomanNumeral(value);
}
static public implicit operator RomanNumeral(BinaryNumeral binary)
{
return new RomanNumeral((int)binary);
}
static public explicit operator int(RomanNumeral roman)
{
return roman.value;
}
static public implicit operator string(RomanNumeral roman)
{
return ("Conversion not yet implemented");
}
}
struct BinaryNumeral
{
private int value;
public BinaryNumeral(int value) //constructor
{
this.value = value;
}
static public implicit operator BinaryNumeral(int value)
{
return new BinaryNumeral(value);
}
static public explicit operator int(BinaryNumeral binary)
{
return (binary.value);
}
static public implicit operator string(BinaryNumeral binary)
{
return ("Conversion not yet implemented");
}
}
class TestConversions
{
static void Main()
{
RomanNumeral roman;
BinaryNumeral binary;
roman = 10;
// Perform a conversion from a RomanNumeral to a BinaryNumeral:
binary = (BinaryNumeral)(int)roman;
// Perform a conversion from a BinaryNumeral to a RomanNumeral:
// No cast is required:
roman = binary;
System.Console.WriteLine((int)binary);
System.Console.WriteLine(binary);
}
}
출력
10 Conversion not yet implemented
강력한 프로그래밍
앞의 예제에 있는 다음 문을 살펴 봅니다.
binary = (BinaryNumeral)(int)roman;
이 문에서는
RomanNumeral
을BinaryNumeral
로 변환합니다.RomanNumeral
에서BinaryNumeral
로 직접 변환되지 않으므로 캐스트를 사용하여RomanNumeral
에서 int로 변환하고 또 다른 캐스트를 사용하여 int에서BinaryNumeral
로 변환합니다.또한 다음 문을 살펴 봅니다.
roman = binary;
이 문에서는
BinaryNumeral
을RomanNumeral
로 변환합니다.RomanNumeral
은BinaryNumeral
로부터의 암시적 변환을 정의하므로 캐스트가 필요하지 않습니다.
참고 항목
개념
C# 프로그래밍 가이드
변환 연산자(C# 프로그래밍 가이드)