Я хотел бы знать причину, позволяющую определять избыточные реализации преобразования в разных классах, но отображать сбой при попытке их использовать.
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;
Есть ли способ специально выбрать конкретную реализацию приведения типа?
Есть ли какая-то причина не предотвращать избыточные реализации фреймворком?
Пожалуйста, ведите меня лучше.