如何在声明时刻分配结构类型?

How to Assign A Structure Type In Declaration Moment?

我声明了一个类型为结构的变量,但是我不能给它赋值

Structure SHAPE
    Dim x as integer
    Dim y as integer
End Structure

Dim Shape1 As SHAPE = (15, 20) ' << The Problem is here

Public Sub test()
    Label1.Text = Shape1.x
End Sub

结构不会神奇地理解您尝试将数据输入其中的任何方式。与任何类型一样,如果您希望能够创建具有特定数据的实例,则添加一个构造函数来执行此操作,例如

Public Structure Shape

    Public ReadOnly Property X As Integer
    Public ReadOnly Property Y As Integer

    Public Sub New(x As Integer, y As Integer)
        Me.X = x
        Me.Y = y
    End Sub

End Structure

然后您可以像创建任何其他类型一样创建该类型的实例:

Dim shape1 As New Shape(15, 20)

要么创建构造器,要么调用构造器。或在构建后填充属性。

例如。

Dim Shape1 As SHAPE = New SHAPE With {.x = 1, .y = 2}

相当于:

Dim Shape1 As SHAPE = New SHAPE()
Shape1.X = 1
Shape1.y = 2

创建构造函数是首选方法,因为结构通常应该是不可变的。这样做并将属性设置为只读是使结构不可变的简单方法:

Public Structure Shape

    Public ReadOnly Property X As Integer
    Public ReadOnly Property Y As Integer

    Public Sub New(x As Integer, y As Integer)
        Me.X = x
        Me.Y = y
    End Sub

End Structure