共用方式為


HOW TO:在物件上執行多項動作 (Visual Basic)

在 Visual Basic 中,通常必須在每個陳述式 (Statement) 中指定物件,用於呼叫該陳述式的其中一個方法或存取它的其中一個屬性。 然而,如果有一系列的陳述式都在同一物件上作業,則可使用 With...End With 結構一次指定所有陳述式的物件。 如此可以使程序執行更快,同時可幫助您避免重複輸入。

範例

下列範列會根據程序引數的值來設定 Label 的前景色彩和字型樣式。

Imports draw = System.Drawing
' The preceding statement must appear at the beginning of the source file.
Dim alertLabel As New System.Windows.Forms.Label
Sub alertUser(ByVal value As Long)
    With alertLabel
        If value = 0 Then
            .ForeColor = draw.Color.Red
            .Font = New draw.Font(.Font, draw.FontStyle.Bold Or draw.FontStyle.Italic)
        Else
            .Forecolor = draw.Color.Black
            .Font = New draw.Font(.Font, draw.FontStyle.Regular)
        End If
    End With
End Sub

記得使用 Or 運算子 (Visual Basic) 來結合字型樣式。 這會指定所要的位元旗標組合。 因為所有 FontStyle 列舉型別 (Enumeration) 成員都使用不同的位元,所以 And 運算子 (Visual Basic) 會產生 0。

同時記得使用 Imports 陳述式 (.NET 命名空間和型別)來建立匯入別名 (Alias) draw,這個匯入別名可縮短 System.Drawing 成員的每個參考且更容易讀取。

將 With...End With 陳述式置入另一個相同的陳述式之中,也可產生巢狀陳述式,如下列程式碼所示:

Sub setupForm()
    Dim anotherForm As New System.Windows.Forms.Form
    Dim button1 As New System.Windows.Forms.Button
    With anotherForm
        .Show()
        .Top = 250
        .Left = 250
        .ForeColor = System.Drawing.Color.LightBlue
        .BackColor = System.Drawing.Color.DarkBlue
        .Controls.Add(button1)
        With .Controls.Item(1)
            .BackColor = System.Drawing.Color.Thistle
            .Text = "Text on button1"
        End With
    End With
End Sub

但在巢狀 With 陳述式內,語法指的是巢狀物件;並未設定外部 With 陳述式中的物件屬性。

請參閱

工作

HOW TO:將控制權轉移出控制結構 (Visual Basic)

HOW TO:處置系統資源 (Visual Basic)

HOW TO:加快存取具有限定性條件長路徑的物件 (Visual Basic)

參考

With...End With 陳述式 (Visual Basic)

概念

決策結構 (Visual Basic)

迴圈結構 (Visual Basic)

其他控制結構 (Visual Basic)

巢狀控制結構 (Visual Basic)

其他資源

Visual Basic 中的控制流程