类型转换重载
可以为一个类自定义到其他类型的转换方式。
被转换类型和目标类型其中至少有一个是声明类的类型。
不能定义到自己继承链上的其他类型的转换。## 显式类型转换
显式转换使用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 化学能();
}