如何使用“With {...}”语法分配属性值?

时间:2017-09-01 22:15:39

标签: vb.net class constructor

在新的Sub New中,我想插入属性值

例: 1级

Public Class A

    Property Name As String

    Sub New()

        MsgBox(Name)   'Empty

    End Sub

End Class

2-表格

    Dim a As New A With {.Name = "ABCDE"}  'MsgBox Empty

1 个答案:

答案 0 :(得分:1)

 Dim a As New A With {.Name = "ABCDE"}  'MsgBox Empty

消息框将为空,因为在上面的语句中,执行顺序为:

  • 调用第一个new并执行子例程new内的所有语句。
  • 然后对with语句中的变量进行初始化步骤。

现在备用解决方案,如果要在初始化期间打印名称:

您可以在属性set期间打印,如下所示。 (当名称设置为值时,可以使用bool变量进一步打印。)

Public Class A

    'PROPERTY GET AND SET
    Private _name As String
    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
            MsgBox(_name) 'PRINT HERE
        End Set
    End Property

    'NEW SUBROUTINE
    Sub New()

    End Sub

End Class

主叫:

 Dim a1 As New A With
            {.Name = "ABCDE"}