与预定义类型的用户类型强制转换
与预定义类型的用户类型强制转换
using System; namespace 实现用户定义的类型强制转换 { class Program { static void Main(string[] args) { //Console.WriteLine("Hello World!"); //隐式转换 //var balance = new Currency(10,50); // float f = balance; //System.Console.WriteLine(balance); // System.Console.WriteLine(f); //显示转换 //下面代码可以成功编译 // float amount = 50.35f; // Currency amount2 = (Currency)amount; // System.Console.WriteLine(amount.ToString()); // Currency c = new Currency(50,35); // float f = c; // c = (Currency)f; // System.Console.WriteLine(c); } } public struct Currency{ public uint Dollars{get;} public ushort Cents{get;} public Currency(uint dollars,ushort cents){ Dollars = dollars; Cents = cents; } public override string ToString()=>$"${Dollars}.{Cents,-2:00}"; //定义一个隐式类型强制转换,将类型Currency强制转换为float。 public static implicit operator float(Currency value)=>value.Dollars+(value.Cents/100f); //反之,要将float转换为类型Currency,就需要显式类型强行转换。 //定义显示强制转换,为了避免数值的丢失,可以使用Convert.ToUInt16(),以及溢出检查。 public static explicit operator Currency(float value){ checked{ uint dollars = (uint)value; ushort cents = Convert.ToUInt16((value - dollars)*100); return new Currency(dollars,cents); } } } }