含蓄
implicit
关键字用于重载转换运算符。例如,你可以声明一个 Fraction
类,它应该在需要时自动转换为 double
,并且可以从 int
自动转换:
class Fraction(int numerator, int denominator)
{
public int Numerator { get; } = numerator;
public int Denominator { get; } = denominator;
// ...
public static implicit operator double(Fraction f)
{
return f.Numerator / (double) f.Denominator;
}
public static implicit operator Fraction(int i)
{
return new Fraction(i, 1);
}
}