c#入门-自定义类型转换

类型转换重载

可以为一个类自定义到其他类型的转换方式。
被转换类型和目标类型其中至少有一个是声明类的类型。
不能定义到自己继承链上的其他类型的转换。## 显式类型转换
显式转换使用explicit operator,返回类型置于参数前。返回类型和参数至少有一个是自己。

动能 a = new 动能();
化学能 b = (化学能)a;

class 动能
{
	public static explicit operator 化学能(动能 L) => new 化学能();

}
class 化学能
{
	public static explicit operator 动能(化学能 L) => new 动能();
}

隐式类型转换

隐式转换使用implicit operator。

动能 a = new 动能();
化学能 b =  a;

class 动能
{
	public static implicit operator 化学能(动能 L) => new 化学能();

}
class 化学能
{
	public static implicit operator 动能(化学能 L) => new 动能();
}

没有传递性

相同的目标类型和发起类型,只能定义其中一种转换声明。
但是隐式转换同时可以作为显示转换来使用。

类型转换没有传递性。如有必要可以使用强制转换的方式手动进行多次转换。

电能 a=  new 电能();
动能 b = (化学能)a;

class 动能
{
	public static implicit operator 化学能(动能 L) => new 化学能();

}
class 化学能
{
	public static implicit operator 动能(化学能 L) => new 动能();
}
class 电能
{
	public static implicit operator 化学能(电能 L) => new 化学能();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值