Why can't coexist implicit and explicit operator of the same type in C#? [duplicate]

只愿长相守 提交于 2019-12-10 16:41:41

问题


Why can not coexist in the same class two operators (explicit and implicit) of the same type? Suppose I have the following:

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;
    }

}

So I can give the client the possibility that use of either of two ways, for example:

Fahrenheit f = new Fahrenheit(20);
Celsius c1 = (Celsius)f;
Celsius c2 = f;

Is there any special reason why this is not allowed or is it just a convention to avoid a misuse of the programmer?


回答1:


According to Overloading Implicit and Explicit Operators page:

That's correct. Defining an implicit operator also allows for explicit conversion. Defining an explicit operator allows only for explicit conversion.

Thus, if you define an explicit operator, you can do the following:

Thing thing = (Thing)"value";

If you define an implicit operator, you can still do the above, but you can also take advantage of implicit conversion:

Thing thing = "value";

So in short, explicit allows only explicit conversion, while implicit allows both explicit and implicit... hence the reason you can only define one.




回答2:


The reason it's not allowed is that it's pointless. The Explicit forces you to cast, the implicit allows you to forget about casting, but still allows you to cast. Implicit extends on the functionality of Explicit. So comment out your Explicit operator and smile :)



来源:https://stackoverflow.com/questions/10892278/why-cant-coexist-implicit-and-explicit-operator-of-the-same-type-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!