带接口的后期绑定技术也许

时间:2012-09-19 12:33:54

标签: vb.net late-binding

请考虑以下情况:

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

问题:如果访问obj1.Func(),条件是由于某种原因我不能从公共接口类继承Class1和Class2?

谢谢

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

    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

1 个答案:

答案 0 :(得分: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)