Tom*_*duy 4 c# operator-overloading implicit-conversion explicit-conversion
为什么不能在同一个类中共存两个相同类型的运算符(显式和隐式)?假设我有以下内容:
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)
是否有任何特殊原因不允许这样做,或者只是避免滥用程序员的惯例?
Mar*_*rco 15
根据Overloading Implicit和Explicit Operators页面:
那是对的.定义隐式运算符也允许显式转换.定义显式运算符仅允许显式转换.
因此,如果定义显式运算符,则可以执行以下操作:
Thing thing = (Thing)"value";如果您定义了一个隐式运算符,您仍然可以执行上述操作,但您也可以利用隐式转换:
Thing thing = "value";所以简而言之,explicit只允许显式转换,而implicit允许显式和隐式......因此你只能定义一个.