C#自定义类型强制转换实例分析
作者:永远爱好写程序 时间:2022-01-14 08:20:06
本文实例讲述了C#自定义类型强制转换的用法。分享给大家供大家参考。具体分析如下:
先来举一个小例子
类定义:
public class MyCurrency
{
public uint Dollars;
public ushort Cents;
public MyCurrency(uint dollars, ushort cents)
{
this.Dollars = dollars;
this.Cents = cents;
}
public override string ToString()
{
return string.Format(
"${0}.{1}", Dollars, Cents
);
}
//提供MyCurrency到float的隐式转换
public static implicit operator float(MyCurrency value)
{
return value.Dollars + (value.Cents / 100.0f);
}
//把float转换为MyCurrency,不能保证转换肯定成功,因为float可以
//存储负值,而MyCurrency只能存储正数
//float存储的数量级比uint大的多,如果float包含一个比unit大的值,
//将会得到意想不到的结果,所以必须定义为显式转换
//float到MyCurrency的显示转换
public static explicit operator MyCurrency(float value)
{
//checked必须加在此处,加在调用函数外面是不会报错的,
//因为溢出的异常是在强制转换运算符的代码中发生的
//Convert.ToUInt16是为了防止丢失精度
//该段内容很重要,详细参考"C#高级编程(中文第七版) 218页说明"
checked
{
uint dollars = (uint)value;
ushort cents = Convert.ToUInt16((value - dollars) * 100);
return new MyCurrency(dollars, cents);
}
}
}
测试代码:
private void btn_测试自定义类型强制转换_Click(object sender, EventArgs e)
{
MyCurrency tmp = new MyCurrency(10, 20);
//调用MyCurrency到float的隐式转换
float fTmp = tmp;
MessageBox.Show(fTmp.ToString());
float fTmp2 = 200.30f;
//调用float到MyCurrency的显示转换
MyCurrency tmp2 = (MyCurrency)fTmp2;
MessageBox.Show(tmp2.ToString());
}
希望本文所述对大家的C#程序设计有所帮助。
标签:C#,类型,转换
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java Servlet 实现动态验证码图片示例
2021-07-14 15:14:28
![](https://img.aspxhome.com/file/2023/8/89958_0s.png)
细品Java8中hashCode方法的使用
2023-10-04 14:01:19
![](https://img.aspxhome.com/file/2023/0/96090_0s.jpg)
SpringBoot集成整合JWT与Shiro流程详解
2022-09-06 06:33:23
![](https://img.aspxhome.com/file/2023/3/81373_0s.png)
WebService教程详解(一)
2022-02-26 09:59:50
整理总结Java多线程程序编写的要点
2022-02-19 16:17:23
![](https://img.aspxhome.com/file/2023/5/103975_0s.jpg)
java关键字static的使用详解
2023-09-24 05:04:11
![](https://img.aspxhome.com/file/2023/1/58181_0s.jpg)
C#基于时间轮调度实现延迟任务详解
2023-07-06 08:00:49
Java用递归方法解决汉诺塔问题详解
2022-11-23 03:11:40
![](https://img.aspxhome.com/file/2023/6/64416_0s.png)
java实现简单扫雷游戏
2022-09-15 13:48:11
Java设计模式之命令模式详解
2023-11-15 21:18:43
Mybatis查询多条记录并返回List集合的方法
2023-08-08 05:16:48
Android Force Close 出现的异常原因分析及解决方法
2021-09-07 18:26:47
Java多线程与线程池技术分享
2021-07-25 07:35:11
![](https://img.aspxhome.com/file/2023/2/80322_0s.jpg)
java判断用户输入的是否至少含有N位小数的实例
2021-06-01 02:56:42
Android操作SQLite数据库(增、删、改、查、分页等)及ListView显示数据的方法详解
2022-11-28 10:03:09
![](https://img.aspxhome.com/file/2023/7/91717_0s.jpg)
Java发送post方法详解
2023-10-28 03:55:00
详解C#如何实现读写ini文件
2022-02-04 23:15:27
![](https://img.aspxhome.com/file/2023/9/82139_0s.png)
详解Java实现数据结构之并查集
2023-09-05 08:47:06
![](https://img.aspxhome.com/file/2023/6/67976_0s.jpg)
Java的静态类型检查示例代码详解
2023-08-09 10:42:13
Spring Data环境搭建实现过程解析
2022-02-26 20:13:38