共用方式為


Visual Basic 6.0 使用者可以進行的預設屬性變更

更新:2007 年 11 月

Visual Basic 2008 為了簡化及加強可讀性,更新了預設的屬性支援。

Visual Basic 6.0

在 Visual Basic 6.0 中,在物件上可支援預設屬性。例如,在 Label 控制項上的預設屬性是 Caption,而下列範例中的兩個指派是相等的。

Dim lbl As Label 
lbl = "Important" 
lbl.Caption = "Important" 

在撰寫 Visual Basic 程式碼時,使用預設屬性可增加撰寫速度,但是它們有幾個缺點:

  • 它們會使程式碼更難閱讀。在上述範例中,如果您不熟悉 Label 控制項,就無法分辨出在第一個指派中,"Important" 字串 (String) 是直接儲存在 lbl 變數,還是儲存在預設屬性中。

  • 以一個您打算在程式碼中使用的物件而言,要探索物件是否有預設屬性並非都很容易,而且就算可以探索出來,也很難確定它到底是什麼屬性。

  • 預設屬性讓 Set 陳述式 (Statement) 成為 Visual Basic 語言中的必要項目。以下範例會顯示如何使用 Set 來表示要指派物件參考 (而不是預設屬性)。

    Dim lbl1 As Label, lbl2 As Label 
    lbl1 = "Saving" ' Assign a value to lbl1's Caption property. 
    lbl2 = lbl1       ' Replace lbl2's Caption property with lbl1's. 
    Set lbl2 = lbl1   ' Replace lbl2 with an object reference to lbl1. 
    

Visual Basic 2008

在 Visual Basic 2008 中,除非預設屬性使用引數,否則不支援預設屬性。因為這項語法變更,Let 和 Set 陳述式對於指定何者會被指派而言並非必要,且在指派陳述式 (Assignment Statement) 中也不會使用它們。在 Label 控制項上,Text 屬性會取代 Caption 屬性,並可使用下列方式重寫前述範例。

Dim L1, L2 As New Label   ' Both become type Label
                          ' in the new version of Visual Basic.
L1.Text = "Saving"        ' Assign Text property. 
L2.Text = L1.Text         ' Copy Text property. 
L2 = L1                   ' Copy object reference.

雖然 Let 在語法上並沒有用處,不過仍然是 Visual Basic 2008 中的保留字。這樣有助於避免將它與先前的意義混淆在一起。Visual Basic 2008 會對設定屬性值的屬性程序使用 Set 陳述式。

參數型屬性

使用引數的預設屬性並非模稜兩可,Visual Basic 2008 也支援這些屬性。預設屬性最常出現在集合類別上。例如,在 System.Windows.Forms 命名空間中,Form 類別支援下列階層架構:

Form 物件

   Controls 屬性 (傳回這個表單的 Control.ControlCollection 物件)

      Control.ControlCollection 物件 (預設屬性為 Item)

         Item 屬性 (傳回集合中某一項目的 Control 物件)

            Control 物件

Controls 屬性會傳回 Control.ControlCollection 物件,而 Item 屬性傳回 Control 物件。下列範例會顯示在 Visual Basic 2008 中,預設屬性的有效及無效使用方式:

Dim F As New Form   ' Assume F has been created and initialized.
F.Controls.Item(0).Text = "Stop"  ' Valid -- no default properties used. 
F.Controls(0).Text = "Stop"  ' Valid -- Item is parameterized. 
'F(0).Text = "Stop"  ' INVALID -- Form does not have a default property. 
'F.Controls(0) = "Stop"  ' INVALID -- No default property on Control. 

預設屬性宣告

在 Visual Basic 2008 中,以 Default 關鍵字來開始屬性宣告,就可以將屬性指定為預設屬性。如果您多載屬性名稱,則必須在每個多載宣告中指定 Default。您無法將預設屬性宣告為 Shared 或 Private。

請參閱

概念

Visual Basic 6.0 使用者可以進行的屬性程序變更

程式設計項目的支援變更摘要

參考

Text

Label

Set 陳述式 (Visual Basic)

System.Windows.Forms

Form

Control.ControlCollection

Control

Default (Visual Basic)