我有一个类,它看起来像这样:
Public Class DataPoint
Private _data As Integer
Private _locInText As Integer
Private _searchValue As String
Property Data As Integer
Get
Return _data
End Get
Set(value As Integer)
_data = value
End Set
End Property
Property LocInText As Integer
Get
Return _locInText
End Get
Set(value As Integer)
_locInText = value
End Set
End Property
Property SearchValue As String
Get
Return _searchValue
End Get
Set(value As String)
_searchValue = value
End Set
End Property
End Class
然后我使用这个类创建另一个类。
Public Class PaintData
Public Time As TimeSpan
Public Color As DataPoint
Public Job As New DataPoint
Public MaxCurrent As New DataPoint
End Class
我想创建一些属性的默认值,即
SearchValue
和 LocInText
。对我来说,在类定义中这样做是有意义的,因为这些本质上是常量。一季度。我应该这样做吗?如果没有,什么是正确的技术。
Q2。我的语法不正确。你能帮我吗?
Public Class PaintData
Public Time As TimeSpan
Public Color As DataPoint
Public Job As New DataPoint
Public MaxCurrent As New DataPoint
Color.LocInText = 4 '<----Declaration expected failure because I'm not in a method
Job.LocInText = 5 '<----Declaration expected failure because I'm not in a method
End Class
谢谢大家
最佳答案
给 DataPoint
一个构造函数:
Public Class DataPoint
Private _data As Integer
Private _locInText As Integer
Private _searchValue As String
Public Sub New(locInText as Integer)
_locInText = locInText
End Sub
'...
End Class
并使用它:
Public Class PaintData
Public Time As TimeSpan
Public Color As New DataPoint(4)
Public Job As New DataPoint(5)
Public MaxCurrent As New DataPoint(6)
End Class
或者你可以使用
Public Property Color As DataPoint = New DataPoint With {.LocInText = 4}
在你的类定义中。这种语法可以说比构造函数语法更具可读性。
关于vb.net - 类属性的默认值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29167149/