为什么不能在C#中同时存在相同类型的隐式和显式运算符? [英] Why can't coexist implicit and explicit operator of the same type in C#?

查看:270
本文介绍了为什么不能在C#中同时存在相同类型的隐式和显式运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能在同一个类中的两个相同类型的运营商(显性和隐性)共存?假设我有以下几点:

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?

推荐答案

据的超载隐显操作符页:

这是正确的。定义一个隐含的运营商还允许
显式转换。定义一个明确的运营商只允许为
显式转换。

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:

事儿事儿=(事)价值;

如果你定义一个隐含的经营者,你仍然可以做上面的,但是
,你还可以利用隐式转换:

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

事儿事儿=值;

因此,在短期,明确只允许显式的转换,而隐
同时允许显性和隐性...因此原因,你只能
定义一个。

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

这篇关于为什么不能在C#中同时存在相同类型的隐式和显式运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆