在字典中收集通用代表

时间:2016-03-21 11:17:11

标签: vb.net generics dictionary delegates

我尝试在字典中收集泛型委托。我做了一个小例子,知道这个例子没有意义。当我尝试将委托添加到字典时,我得到了一个implizit转换警告,我不知道如何解决这个问题。

这是显示警告的行:

m_MyDoSomethings.Add(1, AddressOf myCustomDoSomething)

提示:您必须在项目中激活implizit转换警告,否则您将不会收到此错误。这是一个implizit转换错误,它告诉我无法将类型“BaseDoSomething”转换为“CustomDoSomething”。我不明白为什么他这样做而不是倒退。

Public Class Form1

    Private Delegate Sub DoSomethingDelegate(Of T As BaseDoSomething)(p_DoSomethingClass As T)

    Private m_MyDoSomethings As New Dictionary(Of Short, DoSomethingDelegate(Of BaseDoSomething))

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

        m_MyDoSomethings.Add(1, AddressOf myCustomDoSomething)

    End Sub

    Private Sub myCustomDoSomething(p_CustomDoSomething As CustomDoSomething)
        p_CustomDoSomething.echo()
        p_CustomDoSomething.echo2()
    End Sub

End Class

Public Class BaseDoSomething

    Public Overridable Sub echo()

        MsgBox("echo")

    End Sub

End Class

Public Class CustomDoSomething
    Inherits BaseDoSomething

    Public Overrides Sub echo()

        MsgBox("custom echo")

    End Sub

    Public Sub echo2()

        MsgBox("hello world")

    End Sub

End Class

0 个答案:

没有答案