Covarianza y contravarianza (Visual Basic)Covariance and Contravariance (Visual Basic)

En Visual Basic, la covarianza y la contravarianza habilitan la conversión de referencias implícita de tipos de matriz, tipos de delegado y argumentos de tipo genérico.In Visual Basic, covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments. La covarianza conserva la compatibilidad de asignaciones y la contravarianza la invierte.Covariance preserves assignment compatibility and contravariance reverses it.

El siguiente código muestra la diferencia entre la compatibilidad de asignaciones, la covarianza y la contravarianza.The following code demonstrates the difference between assignment compatibility, covariance, and contravariance.

' Assignment compatibility.   
Dim str As String = "test"  
' An object of a more derived type is assigned to an object of a less derived type.   
Dim obj As Object = str  
  
' Covariance.   
Dim strings As IEnumerable(Of String) = New List(Of String)()  
' An object that is instantiated with a more derived type argument   
' is assigned to an object instantiated with a less derived type argument.   
' Assignment compatibility is preserved.   
Dim objects As IEnumerable(Of Object) = strings  
  
' Contravariance.             
' Assume that there is the following method in the class:   
' Shared Sub SetObject(ByVal o As Object)  
' End Sub  
Dim actObject As Action(Of Object) = AddressOf SetObject  
  
' An object that is instantiated with a less derived type argument   
' is assigned to an object instantiated with a more derived type argument.   
' Assignment compatibility is reversed.   
Dim actString As Action(Of String) = actObject  

La covarianza de matrices permite la conversión implícita de una matriz de un tipo más derivado a una matriz de un tipo menos derivado.Covariance for arrays enables implicit conversion of an array of a more derived type to an array of a less derived type. Pero esta operación no es segura, tal como se muestra en el ejemplo de código siguiente.But this operation is not type safe, as shown in the following code example.

Dim array() As Object = New String(10) {}  
' The following statement produces a run-time exception.  
' array(0) = 10  

La compatibilidad de la covarianza y la contravarianza con grupos de métodos permite hacer coincidir firmas de método con tipos de delegado.Covariance and contravariance support for method groups allows for matching method signatures with delegate types. Esto le permite asignar a los delegados no solo métodos con firmas coincidentes, sino métodos que devuelven tipos más derivados (covarianza) o que aceptan parámetros con tipos menos derivados (contravarianza) que el especificado por el tipo de delegado.This enables you to assign to delegates not only methods that have matching signatures, but also methods that return more derived types (covariance) or that accept parameters that have less derived types (contravariance) than that specified by the delegate type. Para obtener más información, vea Variance in Delegates (Visual Basic) (Varianza en delegados (Visual Basic)) y Using Variance in Delegates (Visual Basic) (Usar varianza en delegados (Visual Basic)).For more information, see Variance in Delegates (Visual Basic) and Using Variance in Delegates (Visual Basic).

En el ejemplo de código siguiente, se muestra la compatibilidad de covarianza y contravarianza con grupos de métodos.The following code example shows covariance and contravariance support for method groups.

Shared Function GetObject() As Object  
    Return Nothing  
End Function  
  
Shared Sub SetObject(ByVal obj As Object)  
End Sub  
  
Shared Function GetString() As String  
    Return ""  
End Function  
  
Shared Sub SetString(ByVal str As String)  
  
End Sub  
  
Shared Sub Test()  
    ' Covariance. A delegate specifies a return type as object,  
    ' but you can assign a method that returns a string.  
    Dim del As Func(Of Object) = AddressOf GetString  
  
    ' Contravariance. A delegate specifies a parameter type as string,  
    ' but you can assign a method that takes an object.  
    Dim del2 As Action(Of String) = AddressOf SetObject  
End Sub  

En .NET Framework 4 o posterior, Visual Basic admite la covarianza y contravarianza en interfaces y delegados genéricos y permite la conversión implícita de parámetros de tipo genérico.In .NET Framework 4 or later, Visual Basic supports covariance and contravariance in generic interfaces and delegates and allows for implicit conversion of generic type parameters. Para obtener más información, vea Variance in Generic Interfaces (Visual Basic) (Varianza en interfaces genéricas (Visual Basic)) y Variance in Delegates (Visual Basic) (Varianza en delegados (Visual Basic)).For more information, see Variance in Generic Interfaces (Visual Basic) and Variance in Delegates (Visual Basic).

En el ejemplo de código siguiente, se muestra la conversión implícita de referencias para interfaces genéricas.The following code example shows implicit reference conversion for generic interfaces.

Dim strings As IEnumerable(Of String) = New List(Of String)  
Dim objects As IEnumerable(Of Object) = strings  

Un delegado o interfaz genéricos se denominan variante si sus parámetros genéricos se declaran como covariantes o contravariantes.A generic interface or delegate is called variant if its generic parameters are declared covariant or contravariant. Visual Basic le permite crear sus propias interfaces y delegados variantes.Visual Basic enables you to create your own variant interfaces and delegates. Para obtener más información, vea Creating Variant Generic Interfaces (Visual Basic) (Crear interfaces genéricas variantes (Visual Basic)) y Variance in Delegates (Visual Basic) (Varianza en delegados (Visual Basic)).For more information, see Creating Variant Generic Interfaces (Visual Basic) and Variance in Delegates (Visual Basic).

TítuloTitle DescripciónDescription
Varianza en interfaces genéricas (Visual Basic)Variance in Generic Interfaces (Visual Basic) Describe la covarianza y contravarianza en las interfaces genéricas y proporciona una lista de interfaces genéricas variantes en .NET Framework.Discusses covariance and contravariance in generic interfaces and provides a list of variant generic interfaces in the .NET Framework.
Crear interfaces genéricas variantes (Visual Basic)Creating Variant Generic Interfaces (Visual Basic) Se muestra cómo crear interfaces variantes personalizadas.Shows how to create custom variant interfaces.
Usar la varianza en interfaces para las colecciones genéricas (Visual Basic)Using Variance in Interfaces for Generic Collections (Visual Basic) Se muestra cómo la compatibilidad de covarianza y contravarianza en las interfaces IEnumerable<T> y IComparable<T> puede ayudarle a volver a usar el código.Shows how covariance and contravariance support in the IEnumerable<T> and IComparable<T> interfaces can help you reuse code.
Varianza en delegados (Visual Basic)Variance in Delegates (Visual Basic) Se describe la covarianza y contravarianza en delegados genéricos y no genéricos y se proporciona una lista de delegados genéricos variantes en .NET Framework.Discusses covariance and contravariance in generic and non-generic delegates and provides a list of variant generic delegates in the .NET Framework.
Usar varianza en delegados (Visual Basic)Using Variance in Delegates (Visual Basic) Se muestra cómo usar la compatibilidad de covarianza y contravarianza en los delegados no genéricos para que coincidan las firmas de método con los tipos de delegado.Shows how to use covariance and contravariance support in non-generic delegates to match method signatures with delegate types.
Usar la varianza para los delegados genéricos Func y Action (Visual Basic)Using Variance for Func and Action Generic Delegates (Visual Basic) Se muestra cómo la compatibilidad de covarianza y contravarianza en los delegados Func y Action puede ayudarle a volver a usar el código.Shows how covariance and contravariance support in the Func and Action delegates can help you reuse code.