//
keywords_operator.cs
// keywords_operator.cs
using System;
namespace Hunts.Keywords
{
// 定义一个人民币结构。数据类型转换的语法对于结构和类是一样的
public struct RMB
{
// 注意:这些数的范围可能不能满足实际中的使用
public uint Yuan;
public uint Jiao;
public uint Fen;
public RMB(uint yuan, uint jiao, uint fen)
{
if (fen > 9)
{
jiao += fen / 10;
fen = fen % 10;
}
if (jiao > 9)
{
yuan += jiao / 10;
jiao = jiao % 10;
}
this.Yuan = yuan;
this.Jiao = jiao;
this.Fen = fen;
}
public override string ToString()
{
return string.Format("¥{0}元{1}角{2}分", Yuan, Jiao, Fen);
}
// 一些操作
public static RMB operator +(RMB rmb1, RMB rmb2)
{
return new RMB(rmb1.Yuan + rmb2.Yuan, rmb1.Jiao + rmb2.Jiao, rmb1.Fen + rmb2.Fen);
}
public static implicit operator float(RMB rmb)
{
return rmb.Yuan + (rmb.Jiao/10.0f) + (rmb.Fen/100.00f);
}
public static explicit operator RMB(float f)
{
uint yuan = (uint)f;
uint jiao = (uint)((f - yuan) * 10);
uint fen = (uint)(((f - yuan) * 100) % 10);
return new RMB(yuan, jiao, fen);
}
// more
}
class App
{
static void Main()
{
RMB r1, r2, r3, r4;
// 记得小学时的某次捐款,我把口袋里藏好的一块钱加6张一毛钱以及13个一分钱的硬币都贡献出去了:(
r1 = new RMB(1, 6, 13);
// 其实当时其他人都已经交过了,他们总共交了:
r2 = new RMB(46, 9, 3);
// 那么加上我的就是:
r3 = r1 + r2;
Console.WriteLine("r3 = {0}", r3.ToString());
// 隐式转换
float f = r3;
Console.WriteLine("float f= {0}", f);
// 显式转换
r4 = (RMB)f;
Console.WriteLine("r4 = {0}", r4.ToString());
//如果不进行显示转换,将出现错误 CS0266: 无法将类型“float”隐式转换为“Hunts.Keywords.RMB”。存在一个显式转换(是否缺少强制转换?)
Console.Read();
}
}
}
请发表评论