Option Infer 陳述式
更新:2007 年 11 月
在宣告變數中啟用區域型別推斷。
Option Infer { On | Off }
參數
On
選擇項,啟用區域型別推斷。Off
選擇項,停用區域型別推斷。
注意事項: |
---|
如果您沒有指定 On 或 Off,在 Visual Basic 2008 中建立的專案會使用預設值 On。從舊版升級的專案則會使用預設值 Off。 |
備註
將 Option Infer 設定為 On 時,不需要明確陳述資料型別便可以宣告變數。編譯器 (Compiler) 會從變數之初始運算式的型別來推斷此變數的資料型別。例如,Option Infer 和 Option Strict 關閉時,Dim someVar = 2 宣告中的變數只會識別為物件。
Option Infer 和 Option Strict 關閉時的 IntelliSense
將 Option Infer 設定為 On 時,編譯器會將 someVar 識別為 Integer。
Option Infer 開啟時的 IntelliSense
編譯器接著可以偵測專案中變數使用上不一致的狀況,而不用等到專案執行發生問題時才辨識。將 someVar 識別為 Integer 同時可讓整合式開發環境 (IDE) 提供完整的 IntelliSense 支援。
注意事項: |
---|
如果您在程式碼或 IDE 中沒有指定 Option Infer 的值,新建立的專案會使用編輯器預設值 Option Infer On。升級的專案則會使用預設值 Option Infer Off。 |
注意事項: |
---|
您的電腦可能會在下列說明中,以不同名稱或位置顯示某些 Visual Studio 使用者介面項目。您所擁有的 Visual Studio 版本以及使用的設定會決定這些項目。如需詳細資訊,請參閱 Visual Studio 設定。 |
若要在檔案中設定 Option Infer
- 在檔案頂端任何其他原始程式碼之前,輸入 Option Infer On 或 Option Infer Off。如果檔案中設定的 Option Infer 值與 IDE 或命令列中設定的值相衝突,檔案中的值有優先權。
若要在 IDE 中設定單一專案的 Option Infer
按一下 [方案總管] 中的專案。
按一下 [檢視] 功能表上的 [屬性頁],開啟 [專案設計工具]。
在 [編譯] 索引標籤的 [Option Infer] 方塊中,按一下 [On] 或 [Off]。
若要在 IDE 中設定 Option Infer 的預設值
在 [工具] 功能表上按一下 [選項]。
展開 [專案和方案] 節點。
按一下 [VB 預設值]。
按一下 [Option Infer] 清單中的 [On] 或 [Off]。
注意事項: 如果您使用 [工具] 功能表設定 Option Infer 的值,則該值會沿用至後續專案,直到您變更為止。
若要在命令列上設定 Option Infer
- 在 vbc 命令中包含 /optioninfer 編譯器選項。
範例
下列範例示範 Option Infer 陳述式如何啟用區域型別推斷。
' Enable Option Infer before trying these examples.
' Variable num is an Integer.
Dim num = 5
' Variable dbl is a Double.
Dim dbl = 4.113
' Variable str is a String.
Dim str = "abc"
' Variable pList is an array of Process objects.
Dim pList = Process.GetProcesses()
' Variable i is an Integer.
For i = 1 To 10
Console.WriteLine(i)
Next
' If CustomerList is a list of Customer objects,
' variable cust is an instance of the Customer class.
For Each cust In CustomerList
Console.WriteLine(cust.Name)
Next
' Variable namedCust is an instance of the Customer class.
Dim namedCust = New Customer With {.Name = "Lance Tucker", _
.City = "Seattle"}
' Variable product is an instance of an anonymous type.
Dim product = New With {Key .Name = "paperclips", Key .Price = 1.29}
' If customers is a collection of Customer objects in the following
' query, the inferred type of cust is Customer, and the inferred type
' of custs is IEnumerable(Of Customer).
Dim custs = From cust In customers _
Where cust.City = "Seattle" _
Select cust.Name, cust.ID