自定义类型强制装换-创新互联
----------------------------------------------------------------------Currency.cs

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();
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
当前文章:自定义类型强制装换-创新互联
网站URL:http://www.jxjierui.cn/article/jgogi.html


咨询
建站咨询
