Out (泛型修饰符) (Visual Basic)

对于泛型类型参数, Out 关键字指定类型为协变。

注解

借助协变,可以使用比泛型参数指定的派生类型更多的派生类型。 这允许隐式转换实现变体接口的类和委托类型的隐式转换。

有关详细信息,请参阅 协变和逆变

规则

可以在泛型接口和委托中使用 Out 关键字。

在泛型接口中,如果类型参数满足以下条件,则可以将其声明为协变:

  • 类型参数仅用作接口方法的返回类型,而不用作方法参数的类型。

    注释

    此规则有一个例外。 如果在协变接口中,有逆变泛型委托作为方法参数,则可以将此协变类型用作此委托的泛型类型参数。 有关协变和逆变泛型委托的详细信息,请参阅委托中的变体以及对 Func 和 Action 泛型委托使用变体

  • 类型参数不用作接口方法的泛型约束。

在泛型委托中,如果类型参数仅用于方法返回类型,而不用于方法参数,则可以将其声明为协变。

引用类型支持协变和逆变,但值类型不支持协变。

在 Visual Basic 中,如果不指定委托类型,则无法在协变接口中声明事件。 此外,协变接口不能有嵌套类、枚举或结构,但它们可以有嵌套接口。

行为

具有协变类型参数的接口使其方法能够返回比类型参数指定的派生类型更多的派生类型。 例如,由于在 .NET Framework 4 中IEnumerable<T>,类型 T 是协变的IEnumerable(Of String),因此可以在不使用任何特殊转换方法的情况下将IEnumerable(Of Object)类型的对象分配给类型的对象。

可以向协变委托分配同一类型的另一个委托,但具有更派生的泛型类型参数。

示例 1

以下示例演示如何声明、扩展和实现协变泛型接口。 它还演示如何对实现协变接口的类使用隐式转换。

' Covariant interface.
Interface ICovariant(Of Out R)
End Interface

' Extending covariant interface.
Interface IExtCovariant(Of Out R)
    Inherits ICovariant(Of R)
End Interface

' Implementing covariant interface.
Class Sample(Of R)
    Implements ICovariant(Of R)
End Class

Sub Main()
    Dim iobj As ICovariant(Of Object) = New Sample(Of Object)()
    Dim istr As ICovariant(Of String) = New Sample(Of String)()

    ' You can assign istr to iobj because
    ' the ICovariant interface is covariant.
    iobj = istr
End Sub

示例 2

以下示例演示如何声明、实例化和调用协变泛型委托。 它还演示如何对委托类型使用隐式转换。

' Covariant delegate.
Public Delegate Function DCovariant(Of Out R)() As R

' Methods that match the delegate signature.
Public Shared Function SampleControl() As Control
    Return New Control()
End Function

Public Shared Function SampleButton() As Button
    Return New Button()
End Function

Private Sub Test()

    ' Instantiating the delegates with the methods.
    Dim dControl As DCovariant(Of Control) =
        AddressOf SampleControl
    Dim dButton As DCovariant(Of Button) =
        AddressOf SampleButton

    ' You can assign dButton to dControl
    ' because the DCovariant delegate is covariant.
    dControl = dButton

    ' Invoke the delegate.
    dControl()
End Sub

另请参阅