具有继承接口的VB.Net调度函数

时间:2015-11-16 15:31:37

标签: vb.net inheritance interface dispatch

我想知道是否有办法使用继承的接口创建一种调度函数。 让我解释 : 假设我们有一个类可以做一些工作并等待一个类型作为基接口的参数(让我们说IBaseInterface)。 在这个类中,我们需要根据接口的类型来分离工作。 我会这样做的:

Public Function DoWork(argument As IBaseInterface) As String
    Return Consume(argument)
End Function

Private Function Consume(int As IBaseInterface) As String
    Return "work for Base Interface Object"
End Function

Private Function Consume(int As IInheritedInterface) As String
    Return "work for inherited Interface Object"
End Function

当我使用实现IBaseInterface的对象调用dowork时,它应该使用IBaseInterface参数进行使用(此时它就像这样工作) 当我用一个实现IInheritedInterface的对象调用dowork时,它应该使用IInheritedInterface调用Consume函数(它不起作用,它总是用IBaseInterface参数调用函数)

有没有办法在不测试对象类型是IBaseInterface还是IInheritedInterface的情况下做这种事情(因为我可以用选择的情况来做这件事但是我认为这不是一个好的编码方式)。

提前致谢

1 个答案:

答案 0 :(得分:0)

由于自动转换,{p> Consume(int As IBaseInterface)始终被调用为DoWork(argument As IBaseInterface)参数始终为IBaseInterface类型,因此重载分辨率与最接近的匹配。如果将参数更改为对象,则应将其匹配。像这样:

Public Function DoWork(argument As Object) As String
    Return Consume(argument)
End Function