Class属性的默认值

时间:2015-03-20 13:01:58

标签: vb.net class

我有一个课,看起来像这样:

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

我想创建一些属性的默认值,namly SearchValueLocInText。对我来说,在类定义中这样做是有意义的,因为它们本质上是常量。

Q1。我应该这样做吗?如果没有,那么适当的技术是什么。

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

全部谢谢

1 个答案:

答案 0 :(得分:4)

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}

在您的班级定义中。这种语法可以说比构造函数语法更具可读性。

相关问题