Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Califique este contenido
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
Visual Studio 2010 - Visual Basic
Option Infer Statement

Enables the use of local type inference in declaring variables.

Option Infer { On | Off }

Term

Definition

On

Optional. Enables local type inference.

Off

Optional. Disables local type inference.

To set Option Infer in a file, type Option Infer On or Option Infer Off at the top of the file, before any other source code. If the value set for Option Infer in a file conflicts with the value set in the IDE or on the command line, the value in the file has precedence.

When you set Option Infer to On, you can declare local variables without explicitly stating a data type. The compiler infers the data type of a variable from the type of its initialization expression.

In the following illustration, Option Infer is turned on. The variable in the declaration Dim someVar = 2 is declared as an integer by type inference.

IntelliSense when Option Infer is on

IntelliSense view of the declaration.

In the following illustration, Option Infer is turned off. The variable in the declaration Dim someVar = 2 is declared as an Object by type inference. In this example, the Option Strict setting is set to Off on the Compile Page, Project Designer (Visual Basic).

IntelliSense when Option Infer is off

IntelliSense view of the declaration.

When a variable is declared as an Object, the run-time type can change while the program is running. Visual Basic performs operations called boxing and unboxing to convert between an Object and a value type. These operations make execution slower. For information about boxing and unboxing, see the Visual Basic Language Specification.

Type inference applies at the procedure level, and does not apply outside a procedure in a class, structure, module, or interface.

For additional information, see Local Type Inference (Visual Basic).

When an Option Infer Statement Is Not Present

If the source code does not contain an Option Infer statement, the Option Infer setting on the Compile Page, Project Designer (Visual Basic) is used. If the command-line compiler is used, the /optioninfer compiler option is used.

To set Option Infer in the IDE

  1. In Solution Explorer, select a project. On the Project menu, click Properties. For more information, see Introduction to the Project Designer.

  2. Click the Compile tab.

  3. Set the value in the Option infer box.

When you create a new project, the Option Infer setting on the Compile tab is set to the Option Infer setting in the VB Defaults dialog box. To access the VB Defaults dialog box, on the Tools menu, click Options. In the Options dialog box, expand Projects and Solutions, and then click VB Defaults. The initial default setting in VB Defaults is On.

To set Option Infer on the command line

  • Include the /optioninfer compiler option in the vbc command.

Default Data Types and Values

The following table describes the results of various combinations of specifying the data type and initializer in a Dim statement.

Data type specified?

Initializer specified?

Example

Result

No

No

Dim qty

If Option Strict is off (the default), the variable is set to Nothing.

If Option Strict is on, a compile-time error occurs.

No

Yes

Dim qty = 5

If Option Infer is on (the default), the variable takes the data type of the initializer. See Local Type Inference (Visual Basic).

If Option Infer is off and Option Strict is off, the variable takes the data type of Object.

If Option Infer is off and Option Strict is on, a compile-time error occurs.

Yes

No

Dim qty As Integer

The variable is initialized to the default value for the data type. For more information, see Dim Statement (Visual Basic).

Yes

Yes

Dim qty As Integer = 5

If the data type of the initializer is not convertible to the specified data type, a compile-time error occurs.

The following examples demonstrate how the Option Infer statement enables local type inference.

Visual Basic
' 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

' Variable item is a string.
Dim lst As New List(Of String) From {"abc", "def", "ghi"}

For Each item In lst
    Console.WriteLine(item)
Next

' Variable namedCust is an instance of the Customer class.
Dim namedCust = New Customer With {.Name = "Blue Yonder Airlines",
                                   .City = "Snoqualmie"}

' Variable product is an instance of an anonymous type.
Dim product = New With {Key .Name = "paperclips", .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

The following example demonstrates that the run-time type can differ when a variable is identified as an Object.

Visual Basic
' Disable Option Infer when trying this example.

Dim someVar = 5
Console.WriteLine(someVar.GetType.ToString)

' If Option Infer is instead enabled, the following
' statement causes a run-time error. This is because
' someVar was implicitly defined as an integer.
someVar = "abc"
Console.WriteLine(someVar.GetType.ToString)

' Output:
'  System.Int32
'  System.String

Date

History

Reason

April 2011

Added information about the Object type, and about type inference.

Information enhancement.

March 2011

Modified the remarks and added an example.

Information enhancement.

Visual Studio 2010 - Visual Basic
Option Infer (instrucción)

Habilita el uso de la inferencia de tipo de variable local al declarar las variables.

Option Infer { On | Off }

Término

Definición

On

Opcional. Habilita la inferencia de tipo de variable local.

Off

Opcional. Deshabilita la inferencia de tipo de variable local.

Para establecer Option Infer en un archivo, escriba Option Infer On o Option Infer Off en la parte superior del archivo, antes de cualquier otro código fuente. Si el valor que se establece para Option Infer en un archivo está en conflicto con el valor establecido en el IDE o la línea de comandos, tiene prioridad el valor del archivo.

Al establecer Option Infer en On, puede declarar las variables locales sin especificar explícitamente un tipo de datos. El compilador deduce el tipo de datos de una variable a partir del tipo de su expresión de inicialización.

En la siguiente ilustración, Option Infer está activada. La variable de la declaración Dim someVar = 2 se declara como un entero por inferencia de tipos.

IntelliSense cuando está activada la instrucción Option Infer

Vista IntelliSense de la declaración.

En la siguiente ilustración, Option Infer está desactivada. La variable de la declaración Dim someVar = 2 se declara como un Object por inferencia de tipos. En este ejemplo, el valor de Option Strict se establece en Off en Página Compilación, Diseñador de proyectos (Visual Basic).

IntelliSense cuando está desactivada la instrucción Option Infer

Vista IntelliSense de la declaración.

Cuando se declara una variable como un Object, puede cambiar el tipo en tiempo de ejecución mientras se ejecuta el programa. Visual Basic realiza operaciones llamadas conversión boxing y conversión unboxing para convertir entre un Object y un tipo de valor. Estas operaciones ralentizan la ejecución. Para obtener información acerca de las conversiones boxing y unboxing, vea Especificación del lenguaje de Visual Basic.

La inferencia de tipos se aplica en el nivel de procedimiento, y no se aplica fuera de un procedimiento en una clase, estructura, módulo o interfaz.

Para obtener información adicional, vea Inferencia de tipo de variable local (Visual Basic).

Cuando no existe una instrucción Option Infer

Si el código fuente no contiene una instrucción Option Infer, se utiliza el valor de Option Infer en Página Compilación, Diseñador de proyectos (Visual Basic). Si se utiliza el compilador de línea de comandos, se utiliza la opción del compilador /optioninfer.

Para establecer Option Infer en el IDE

  1. En el Explorador de soluciones, seleccione un proyecto. En el menú Proyecto, haga clic en Propiedades. Para obtener más información, vea Introducción al Diseñador de proyectos.

  2. Haga clic en la ficha Compilar.

  3. Establezca el valor en la casilla Option infer.

Cuando se crea un nuevo proyecto, el valor de Option Infer en la pestaña Compilación se establece en el valor de Option Infer en el cuadro de diálogo Valores predeterminados de VB. Para obtener acceso al cuadro de diálogo Valores predeterminados de VB, en el menú Herramientas, haga clic en Opciones. En el cuadro de diálogo Opciones, expanda Proyectos y soluciones y, a continuación, haga clic en Valores predeterminados de VB. El valor predeterminado inicial de Valores predeterminados de VB es On.

Para establecer Option Infer en la línea de comandos

  • Incluya la opción del compilador /optioninfer en el comando vbc.

Valores y tipos de datos predeterminados

La tabla siguiente describe los resultados de varias combinaciones de especificar el tipo de datos y el inicializador en una instrucción Dim.

¿Tipo de datos especificado?

¿Inicializador especificado?

Ejemplo

Resultado

No

No

Dim qty

Si Option Strict está desactivada (el valor predeterminado), la variable se establece en Nothing.

Si Option Strict está activada, se produce un error en tiempo de compilación.

No

Dim qty = 5

Si Option Infer está activada (el valor predeterminado), la variable toma el tipo de datos del inicializador. Vea Inferencia de tipo de variable local (Visual Basic).

Si Option Infer y Option Strict están desactivadas, la variable toma el tipo de datos de Object.

Si Option Infer está desactivada y Option Strict está activada, se produce un error en tiempo de compilación.

No

Dim qty As Integer

La variable se inicializa con el valor predeterminado para el tipo de datos. Para obtener más información, vea Instrucción Dim (Visual Basic).

Dim qty As Integer = 5

Si el tipo de datos del inicializador no es convertible al tipo de datos especificado, se produce un error en tiempo de compilación.

En los ejemplos siguientes se muestra cómo la instrucción Option Infer habilita la inferencia de tipo de variable local.

Visual Basic
' 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

' Variable item is a string.
Dim lst As New List(Of String) From {"abc", "def", "ghi"}

For Each item In lst
    Console.WriteLine(item)
Next

' Variable namedCust is an instance of the Customer class.
Dim namedCust = New Customer With {.Name = "Blue Yonder Airlines",
                                   .City = "Snoqualmie"}

' Variable product is an instance of an anonymous type.
Dim product = New With {Key .Name = "paperclips", .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

El ejemplo siguiente demuestra que el tipo en tiempo de ejecución puede variar cuando se identifica una variable como un Object.

Visual Basic
' Disable Option Infer when trying this example.

Dim someVar = 5
Console.WriteLine(someVar.GetType.ToString)

' If Option Infer is instead enabled, the following
' statement causes a run-time error. This is because
' someVar was implicitly defined as an integer.
someVar = "abc"
Console.WriteLine(someVar.GetType.ToString)

' Output:
'  System.Int32
'  System.String

Fecha

Historial

Motivo

1 de abril de 2011

Información adicional acerca del tipo Object y sobre la inferencia de tipos.

Mejora de la información.

Marzo de 2011

Modificadas las observaciones y agregado un ejemplo.

Mejora de la información.

Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Temas legales | Marcas Registradas | Declaración de privacidad
Page view tracker