0

请考虑以下场景:

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

问题:如果由于某种原因我无法从公共接口类继承 Class1 和 Class2,如何访问 obj1.Func()?

谢谢

更新:我用来解决问题但失败的一种方法如下:

    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
4

1 回答 1

0

你可以试试这个

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

或者你也可以试试

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

或者您可以尝试使用反射。

Dim result as String = obj1.GetType().GetMethod("Func").Invoke(obj1, null)
于 2012-09-19T12:41:49.583 回答