我正在构建一个使用物理属性测量的应用程序。起初,我用了一大堆的类型“双”的变量,并在匈牙利命名法或在我的头上不停值的轨迹:测试通用类型实现接口并使用该接口
Public Class ResultData
Public Property position_in_mm_vs_time_in_ms as Double(,)
Public Property initial_position_in_mm as Double
Public Property final_position_in_mm as Double
Public Property duration_in_ms as Double
Public Property speed_in_mm_per_s as Double
End Class
但我增加了更多的项目,更多的属性这迅速成为一个烂摊子,转换因子洒满了,没有办法知道某个值是以米还是毫米为单位的,没有办法知道项目的正确缩写是没有硬编码和手动跟踪的,以及为输入和输出添加选项的想法SI或英制单位的数据是可怕的。
我意识到这个问题是一个打字的问题,那我可以使用一类具有类型和值来提高这种安排:
Namespace Measure
Public Class Value(Of GenericUnits)
Public Property Value As Double
End Class
Public Class ValuePoint(Of XUnits, YUnits)
Public X As Value(Of XUnits)
Public Y As Value(Of YUnits)
Public Sub New(x As Value(Of XUnits), y As Value(Of YUnits))
Me.X = x
Me.Y = y
End Sub
End Class
Public Class Units
Public Interface GenericUnits
ReadOnly Property Abbreviation As String
' Additional properties, operators, and conversion functions
End Interface
' Additional unit types
End Class
End Namespace
所以我的声明变成了:
Public Class ResultData
Public Property PositionData as List(of ValuePoint(of Units.Seconds, Units.Millimeters))
Public Property InitialPosition as Value(of Units.Millimeters)
Public Property FinalPosition as Value(of Units.Millimeters)
Public Property Duration as Value(of Units.Milliseconds)
Public Property Speed as Value(of Units.MillimetersPerSecond)
End Class
这真的很好,干净。现在,我想用我的运营商定义的属性和转换,但我不能:
Dim result As New ResultData()
Dim msg As New System.Text.StringBuilder()
msg.AppendLine("Speed units are abbreviated as: ")
msg.AppendLine(result.Speed.GetType().ToString() & "?")
msg.AppendLine(result.Speed.GetType().GenericTypeArguments(0).ToString() & "?")
' Produces error "Abbreviation is not a member of System.Type"
' Casting produces conversion error
'msg.AppendLine(result.Speed.GetType().GenericTypeArguments(0).Abbreviation & "?")
' Produces:
' Speed units are abbreviated as:
' Measure.Value`1[Measure.Units+MillimetersPerSecond]
' Measure.Units+MillimetersPerSecond
MsgBox(msg.ToString())
如何访问我的类型声明的属性和方法?
我发现我的声明Value(Of GenericUnits)
实际上并没有引用名为GenericUnits
的接口,而是产生一个泛型类型;我不妨称它为Value(Of T)
。我认为这可能与我的问题有关。
这似乎是明智的。关于你的最终评论,是不是一个完全抽象的基类会要求你重新实现这些方法?看来我们真的想要一个完整的基类。 – kvermeer
@kvermeer标记类抽象(VB:MustInherit)只是意味着您必须从中继承,并且无法直接创建实例。您可以在MustInherit类型中使用具体的方法。 –
啊,这很有道理!谢谢。似乎现在工作顺利.... – kvermeer