【发布时间】:2012-06-05 05:54:15
【问题描述】:
为什么不能在同一类中同时存在同一类型的两个运算符(显式和隐式)?假设我有以下内容:
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;
是否有任何特殊原因不允许这样做,或者只是为了避免滥用程序员的约定?
【问题讨论】:
-
不允许编译吗?你得到什么错误?
-
@gideon: 重复的用户定义转换...
-
@gideon:在编译器时重复的用户定义转换;)
标签: c# operator-overloading implicit-conversion explicit-conversion