我很难从一个多次重载的子程序中选择正确的子程序,每个子程序都有两个参数。也许某种形式的双重分派是合适的,但是当有两个参数需要检查两个(可能)不同的类型时,我看不到任何整洁的方法。
从本质上讲,我创建的示例代码可以按需要执行,但在我看来这是一种非常糟糕的方法。由于类型是在编译时确定的,因此我不能通过传入我要测试的两个对象来简单地调用我想要的 sub:
test(store(0),store(1))
只会调用带有签名的测试子程序
Sub test(cA As Class1, cB As Class1)
因为 store(x) 的静态类型总是 Class1。
某种复杂的双重调度形式可行还是有更好的解决方案?
Option Strict On
Module Module1
Sub Main()
Dim store As List(Of Class1) = New List(Of Class1)
store.Add(New Class2)
store.Add(New Class3)
If TypeOf (store(0)) Is Class2 Then
If TypeOf store(1) Is Class2 Then
test(CType(store(0), Class2), CType(store(1), Class2))
ElseIf TypeOf store(1) Is Class3 Then
test(CType(store(0), Class2), CType(store(1), Class3))
'and so on...
End If
ElseIf TypeOf (store(0)) Is Class3 Then
'relevant tests of store(1)
ElseIf TypeOf (store(0)) Is Class4 Then
'relevant tests of store(1)
End If
Console.ReadLine()
End Sub
Sub test(cA As Class2, cB As Class2)
Console.WriteLine(cA.class2SecondUniqueProperty)
Console.WriteLine("2 and a 2")
End Sub
Sub test(cA As Class2, cB As Class3)
Console.WriteLine("2 and a 3")
End Sub
Sub test(cA As Class2, cB As Class4)
Console.WriteLine(cB.class4UniqueProperty)
Console.WriteLine("2 and a 4")
End Sub
Sub test(cA As Class3, cB As Class2)
Console.WriteLine("3 and a 2")
End Sub
Sub test(cA As Class3, cB As Class3)
Console.WriteLine("3 and a 3")
End Sub
Sub test(cA As Class3, cB As Class4)
Console.WriteLine("3 and a 4")
End Sub
'and so on, for many (but not all) pairs of classes inherited from Class 1.
Public Class Class1
End Class
Public Class Class2
Inherits Class1
Property class2UniqueProperty As String = "only present in Class 2"
Property class2SecondUniqueProperty As String = "only present in Class 2"
Sub class2UniqueSub()
'do something that the other classes derrived from Class1 don't
End Sub
End Class
Public Class Class3
Inherits Class1
Property class3UniqueProperty As String = "only present in Class 3"
End Class
Public Class Class4
Inherits Class1
Property class4UniqueProperty As String = "only present in Class 4"
End Class
'will be more than 4 classes
End Module