vb.net Class 属性的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29167149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:54:16  来源:igfitidea点击:

Default values of Class properties

vb.netclass

提问by user432209

I have a class, it looks like this:

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

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

I then create another class using this class.

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

Public Class PaintData
    Public Time As TimeSpan
    Public Color As DataPoint
    Public Job As New DataPoint
    Public MaxCurrent As New DataPoint
End Class

I want to create default values of some of the properties, namly SearchValueand LocInText. To me, it makes sense to do this inside the class definition, because these are essentially constants.

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

Q1. Should I be doing it this way? If not, what is the proper technique.

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

Q2. I can't get the syntax right. Can you help?

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

Thanks all

谢谢大家

回答by James Thorpe

Give DataPointa constructor:

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

And use that:

并使用它:

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

Alternatively you could use

或者你可以使用

Public Property Color As DataPoint = New DataPoint With {.LocInText = 4}

in your class definition. This syntax is arguably more readable than the constructor syntax.

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