[C#] Implicit Operator 암시적 형변환
implicit operatorPermalink
예시Permalink
간단한 구조체와 float형이 자동으로 변환할 수 있게 해주는 코드이다.
public struct Millimeter
{
public float Value;
Millimeter(float num)
{
this.Value = num;
}
// Millimeter 구조체형에서 float형으로 암시적 형변환을 구현한다.
public static implicit operator float(Millimeter num)
{
return num.Value * 1000;
}
// float형에서 Millimeter 구조체로 암시적 형변환을 구현한다.
public static implicit operator Millimeter(float num)
{
return new Millimeter(num / 1000.0f);
}
}
class Program
{
static void Main(string[] args)
{
// 암시적 형변환을 구현하여 float형을 바로 대입할 수 있음
Millimeter myMil = 10;
// 0.01 출력
Console.WriteLine(myMil.Value);
}
}
댓글남기기