----------------------------------------------------------------------Currency.cs
创新互联建站始终坚持【策划先行,效果至上】的经营理念,通过多达10余年累计超上千家客户的网站建设总结了一套系统有效的全网营销推广解决方案,现已广泛运用于各行各业的客户,其中包括:成都水泥搅拌车等企业,备受客户赞扬。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { //类和结构相似 public struct Currency { private uint dollars; //元 private ushort cents; //分 public Currency(uint i, ushort s)//初始化构造函数 { this.dollars = i; this.cents = s; } public override string ToString() { return string.Format("{0}.{1,2:00}", dollars, cents); } //看情况选择是显示装换还是隐式转换,(uint和ushort都可以隐式转换为float) //重载运算符必须使用public static //implicit 隐式转换 //把Currency对象隐式转换为float类型 public static implicit operator float(Currency c) { return c.dollars + c.cents / 100.0f; } //explicit为显式转换 //把float对象显式转换为Currency类型 public static explicit operator Currency(float f) { checked//溢出则抛出异常 { uint i = (uint)f; ushort s = Convert.ToUInt16((f - i) * 100); return new Currency(i, s); } } } }
----------------------------------------------------------------------主程序
Currency c = new Currency(50, 35); float f = (float)(c); c = (Currency)f; Console.WriteLine(c.ToString()); Console.ReadKey();
文章标题:自定义类型强制装换
当前路径:https://www.cdcxhl.com/article14/jcjode.html
成都网站建设公司_创新互联,为您提供微信小程序、静态网站、网站建设、定制开发、手机网站建设、企业建站
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联