Late Binding Technique with Interface perhaps
-
02-07-2021 - |
Question
Please consider the following scenario:
Class Class1
Function Func() as String
End Function
End Class
Class Class2
Function Func() as String
End Function
Function Func2() as String
End Function
End Class
Class Class3
Function GetClassObject as Object
If (certain condition meets)
return new Class1();
Else
return new Class2();
End If
End Function
Main()
Object obj1 = GetClassObject();
obj1.Func(); // Error: obj1.Func() is not defined:
End Main
End Class
Question: How to access obj1.Func() given the condition that for some reason I cannot inherit Class1 and Class2 from a common Interface class?
Thank you
Update: One approach I used to address the problem and failed is as follows:
Interface ICommon
Function Func() as string
End Interface
Class Class3
...
Main()
Dim obj1 as ICommon = TryCast(GetClassObject(), ICommon); //Error: obj1 is "Nothing"
obj1.Func()
or simply:
TryCast(GetClassObject(), ICommon).Func() //Error: obj1 is Nothing
End Main
...
End Class
Solution
You can try this
Object obj1 = GetClassObject();
If TypeOf obj1 Is Class1 Then
DirectCast(obj1 , Class1).Func()
ElseIf TypeOf obj1 Is Class2 Then
DirectCast(obj1 , Class2).Func()
End If
Or You can also try
Dim c1 As Class1 = TryCast(obj1, Class1)
IF Not c1 Is Nothing Then
c1.Func()
Else
Dim c2 As Class2 = TryCast(obj1, Class2)
IF Not c2 Is Nothing Then
c2.Func()
End If
End If
Or you can try With Reflection.
Dim result as String = obj1.GetType().GetMethod("Func").Invoke(obj1, null)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow