含蓄
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);
}
}