對於泛型型別參數, In 關鍵詞會指定類型參數為反變數。
備註
Contravariance 可讓您使用比泛型參數指定的衍生類型少。 這允許隱含轉換實作 Variant 介面的類別,以及委派類型的隱含轉換。
如需詳細資訊,請參閱 共變數和反變數。
規則
您可以在泛型介面和委派中使用 In 關鍵詞。
如果型別參數只做為方法自變數類型,而且不能當做方法傳回型別使用,則可以在泛型介面中宣告為反變數或委派。
ByRef 參數不可以是 covariant 或 contravariant。
參考型別支援共變數和反變數,而實值型別則不支援。
在 Visual Basic 中,您無法在未指定委派類型的情況下,在反變數介面中宣告事件。 此外,Contravariant 介面不能有巢狀類別、列舉或結構,但它們可以有巢狀介面。
行為
具有反變數型別參數的介面可讓其方法接受衍生型別自變數比介面類型參數所指定的自變數還要少。 例如,由於在 .NET Framework 4 中,在 介面中IComparer<T>,T 類型為反變數,因此,如果繼承自 Person,您可以將型別的物件IComparer(Of Person)指派給型別的物件IComparer(Of Employee),而不需要使用任何特殊的轉換方法Employee。
反變數委派可以指派相同類型的另一個委派,但具有較不衍生的泛型型別參數。
範例 - contravariant 泛型介面
下列範例示範如何宣告、擴充及實作Contravariant泛型介面。 它也會示範如何針對實作這個介面的類別使用隱含轉換。
' Contravariant interface.
Interface IContravariant(Of In A)
End Interface
' Extending contravariant interface.
Interface IExtContravariant(Of In A)
Inherits IContravariant(Of A)
End Interface
' Implementing contravariant interface.
Class Sample(Of A)
Implements IContravariant(Of A)
End Class
Sub Main()
Dim iobj As IContravariant(Of Object) = New Sample(Of Object)()
Dim istr As IContravariant(Of String) = New Sample(Of String)()
' You can assign iobj to istr, because
' the IContravariant interface is contravariant.
istr = iobj
End Sub
範例 - contravariant 泛型委派
下列範例示範如何宣告、具現化及叫用反變數泛型委派。 它也會示範如何隱含地轉換委派類型。
' Contravariant delegate.
Public Delegate Sub DContravariant(Of In A)(ByVal argument As A)
' Methods that match the delegate signature.
Public Shared Sub SampleControl(ByVal control As Control)
End Sub
Public Shared Sub SampleButton(ByVal control As Button)
End Sub
Private Sub Test()
' Instantiating the delegates with the methods.
Dim dControl As DContravariant(Of Control) =
AddressOf SampleControl
Dim dButton As DContravariant(Of Button) =
AddressOf SampleButton
' You can assign dControl to dButton
' because the DContravariant delegate is contravariant.
dButton = dControl
' Invoke the delegate.
dButton(New Button())
End Sub