我想知道允许在不同的类中定义冗余转换实现,但在尝试使用它们时显示失败的原因。
public class Celsius
{
public Celsius(float temp)
{
Degrees = temp;
}
public float Degrees { get; }
public static explicit operator Fahrenheit(Celsius c)
{
return new Fahrenheit((9.0f / 5.0f) * c.Degrees + 32);
}
public static explicit operator Celsius(Fahrenheit fahr)
{
return new Celsius((5.0f / 9.0f) * (fahr.Degrees - 32));
}
}
public class Fahrenheit
{
public Fahrenheit(float temp)
{
Degrees = temp;
}
public float Degrees { get; }
public static explicit operator Fahrenheit(Celsius c)
{
return new Fahrenheit((9.0f / 5.0f) * c.Degrees + 32);
}
public static explicit operator Celsius(Fahrenheit fahr)
{
return new Celsius((5.0f / 9.0f) * (fahr.Degrees - 32));
}
}
上面的代码将不会显示任何错误。但是在尝试使用它时,它将显示模棱两可的代码实现错误。
Fahrenheit fahr = new Fahrenheit(100.0f);
Celsius c = (Celsius)fahr;
Console.Write($" = {c.Degrees} Celsius");
Fahrenheit fahr2 = (Fahrenheit)c;
是否有一种方法可以专门选择特定的类型转换实现? 框架不阻止多余的实现背后有什么原因吗? 请以更好的方式指导我。
答案 0 :(得分:2)
对于每种类型,您不必都需要2个强制转换运算符。您应该只在Fahrenheit
类中进行C到F的转换,反之亦然。