共用方式為


在委派中使用變異數 (C# 和 Visual Basic)

當您指派方法給委派時,共變數 和 Contravariance 會提供比對委派型別與方法簽章的彈性。 Covariance 允許方法擁有比定義於委派內更為衍生的傳回型別, Contravariance 則允許方法擁有比委派型別 (Delegate Type) 內更少的衍生參數型別。

範例 1:Covariance

描述

這個範例會示範如何搭配具有傳回型別的方法來使用委派,該傳回型別是衍生自委派簽章內的傳回型別。 由 DogsHandler 傳回的資料型別具有 Dogs 型別,該型別是衍生自委派內所定義的 Mammals 型別。

程式碼

Class Mammals
End Class

Class Dogs
    Inherits Mammals
End Class
Class Test
    Public Delegate Function HandlerMethod() As Mammals
    Public Shared Function MammalsHandler() As Mammals
        Return Nothing
    End Function
    Public Shared Function DogsHandler() As Dogs
        Return Nothing
    End Function
    Sub Test()
        Dim handlerMammals As HandlerMethod = AddressOf MammalsHandler
        ' Covariance enables this assignment.
        Dim handlerDogs As HandlerMethod = AddressOf DogsHandler
    End Sub
End Class
class Mammals{}
class Dogs : Mammals{}

class Program
{
    // Define the delegate.
    public delegate Mammals HandlerMethod();

    public static Mammals MammalsHandler()
    {
        return null;
    }

    public static Dogs DogsHandler()
    {
        return null;
    }

    static void Test()
    {
        HandlerMethod handlerMammals = MammalsHandler;

        // Covariance enables this assignment.
        HandlerMethod handlerDogs = DogsHandler;
    }
}

範例 2:Contravariance

描述

這個範例將示範如何搭配具有型別之參數的方法來使用委派,該型別是委派簽章參數型別的基底型別 (Base Type)。 使用 Contravariance 時,您可以使用一個事件處理常式取代個別的處理常式。 例如,您可以建立事件處理常式,接受 EventArgs 輸入參數,並搭配使用它與傳送 MouseEventArgs 型別做為參數的 Button.MouseClick 事件,以及傳送 KeyEventArgs 參數的 TextBox.KeyDown 事件。

程式碼

' Event hander that accepts a parameter of the EventArgs type.
Private Sub MultiHandler(ByVal sender As Object,
                         ByVal e As System.EventArgs)
    Label1.Text = DateTime.Now
End Sub

Private Sub Form1_Load(ByVal sender As System.Object,
    ByVal e As System.EventArgs) Handles MyBase.Load

    ' You can use a method that has an EventArgs parameter,
    ' although the event expects the KeyEventArgs parameter.
    AddHandler Button1.KeyDown, AddressOf MultiHandler

    ' You can use the same method 
    ' for the event that expects the MouseEventArgs parameter.
    AddHandler Button1.MouseClick, AddressOf MultiHandler
End Sub
// Event hander that accepts a parameter of the EventArgs type.
private void MultiHandler(object sender, System.EventArgs e)
{
    label1.Text = System.DateTime.Now.ToString();
}

public Form1()
{
    InitializeComponent();

    // You can use a method that has an EventArgs parameter,
    // although the event expects the KeyEventArgs parameter.
    this.button1.KeyDown += this.MultiHandler;

    // You can use the same method 
    // for an event that expects the MouseEventArgs parameter.
    this.button1.MouseClick += this.MultiHandler;

}

請參閱

參考

針對 Func 與 Action 委派使用變異數 (C# 和 Visual Basic)

概念

委派中的變異數 (C# 和 Visual Basic)