类属性的默认值

use*_*209 4 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
Run Code Online (Sandbox Code Playgroud)

然后,我使用该类创建另一个类。

Public Class PaintData
    Public Time As TimeSpan
    Public Color As DataPoint
    Public Job As New DataPoint
    Public MaxCurrent As New DataPoint
End Class
Run Code Online (Sandbox Code Playgroud)

我想创建某些属性的默认值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
Run Code Online (Sandbox Code Playgroud)

谢谢大家

Jam*_*rpe 5

给出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
Run Code Online (Sandbox Code Playgroud)

并使用:

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
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用

Public Property Color As DataPoint = New DataPoint With {.LocInText = 4}
Run Code Online (Sandbox Code Playgroud)

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