为什么不能在C#中共存相同类型的隐式和显式运算符?
为什么不能在同一个类中共存两个相同类型的运算符(显式和隐式)? 假设我有以下内容:
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; } }
所以我可以给客户端使用两种方式中的任何一种,例如:
Fahrenheit f = new Fahrenheit(20); Celsius c1 = (Celsius)f; Celsius c2 = f;
是否有任何特殊原因不允许这样做,或者只是避免误用程序员的惯例?
根据Overloading Implicit和Explicit Operators页面:
那是对的。 定义隐式运算符也允许显式转换。 定义显式运算符仅允许显式转换。
因此,如果定义显式运算符,则可以执行以下操作:
Thing thing = (Thing)"value";
如果您定义了隐式运算符,您仍然可以执行上述操作,但您也可以利用隐式转换:
Thing thing = "value";
所以简而言之,explicit只允许显式转换,而implicit允许显式和隐式……因此你只能定义一个。
它不被允许的原因是它没有意义。 Explicit强制你施放,隐式允许你忘记施法,但仍允许你施放。 隐式扩展了Explicit的function。 所以注释掉你的Explicit运算符并微笑:)