为什么不能在同一个类中共存两个相同类型的运算符(显式和隐式)?假设我有以下内容:
public class Fahrenheit
{
public float Degrees { get; set; }
public Fahrenheit(float degrees)
{
Degrees = degrees;
}
public static explicit operator Celsius(Fahrenheit f)
{
return new Celsius(ToCelsius(f.Degrees));
}
public static implicit operator Celsius(Fahrenheit f)
{
return new Celsius(ToCelsius(f.Degrees));
}
}
public class Celsius {
public float Degrees { get; set; }
public Celsius(float degrees)
{
Degrees = degrees;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以给客户端使用两种方式中的任何一种,例如:
Fahrenheit f = new Fahrenheit(20);
Celsius c1 = (Celsius)f;
Celsius c2 = f;
Run Code Online (Sandbox Code Playgroud)
是否有任何特殊原因不允许这样做,或者只是避免滥用程序员的惯例?
c# operator-overloading implicit-conversion explicit-conversion