vb.net - 类属性的默认值

标签 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

我想创建一些属性的默认值,即 SearchValueLocInText。对我来说,在类定义中执行此操作是有意义的,因为这些本质上是常量。

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

第二季度。我无法正确理解语法。你能帮忙吗?

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/

相关文章:

vb.net - 通过重复获得组合

sql - 从 DataGridView 更新 SQL

vb.net - 为参数表达式定义完整方法

返回Generic Class类型时Java编译错误

class - 根据一台机器上安装的类选择 puppet 模板

vb.net - 按需显示或隐藏标题栏

c# - 如何在同一个 Visual Studio 解决方案中设置 ASP Classic 和 ASP.NET WebForm - 用于在 ASP.NET WebForm 中重写 ASP Classic 页面

c++ - 如何创建一个存储指向成员函数的指针的类(C++)

c++ - 创建类对象的无序映射

ios委托(delegate)方法未被调用