我非常喜欢Nathan Wong的这篇文章Make the Type System Do the Work,但我很难按照代码示例,因为我不熟悉C ++。你会如何用VB.NET或C#编写这个C ++代码?
struct Degrees
{
double val;
Degrees(double _val) : val(_val) {}
};
struct DegCelsius : public Degrees
{
DegCelsius(double deg) : Degrees(deg) {}
DegCelsius(const DegFahrenheit °)
: Degrees((deg.val - 32) * 5 / 9) {}
};
struct DegFahrenheit : public Degrees
{
DegFahrenheit(double deg) : Degrees(deg) {}
DegFahrenheit(const DegCelsius °)
: Degrees(deg.val * 9 / 5 + 32) {}
};
DegFahrenheit input(68);
DegCelsius temperature = input;
答案 0 :(得分:1)
我认为这可以改进一些方法。 VB.NET版本:
Public MustInherit Class Degrees
Public Property val As Decimal
End Class
Public Class DegFahrenheit
Inherits Degrees
Public Sub New(ByVal deg As Decimal)
Me.val = deg
End Sub
Public Sub New(ByVal degCel As DegCelsius)
Me.val = degCel.val * 9 / 5 + 32
End Sub
Public Shared Widening Operator CType(ByVal Celsius As DegCelsius) As DegFahrenheit
Return New DegFahrenheit(Celsius)
End Operator
End Class
Public Class DegCelsius
Inherits Degrees
Public Sub New(ByVal deg As Decimal)
Me.val = deg
End Sub
Public Sub New(ByVal fahrenheit As DegFahrenheit)
Me.val = (fahrenheit.val - 32) * 5 / 9
End Sub
Public Shared Widening Operator CType(ByVal Farenheit As DegFahrenheit) As DegCelsius
Return New DegCelsius(Farenheit)
End Operator
End Class
进行测试:
Dim Input = New DegFahrenheit(68) 'Val = 68
Dim Celsius As DegCelsius = Input 'Val = 20
Dim Fahrenheit As DegFahrenheit = Celsius 'Val = 68
作为一个不必要的补充,我想要调试将其添加到Degrees类中,以便该值显示在本地而不需要展开:
Public Overrides Function ToString() As String
Return val
End Function