我有一个BaseClass,一个DerivedClass1和一个来自第三方库的DerivedClass2. DerivedClass1和DerivedClass2都从BaseClass继承. 有一个来自同一个库的ContainerClass,它有一个成员变量ActiveItem,它可以是DerivedCla
有一个来自同一个库的ContainerClass,它有一个成员变量ActiveItem,它可以是DerivedClass1或DerivedClass2,所以它被声明为BaseClass.
我想知道ActiveItem是否属于DerivedClass1,因为它可以在运行时更改,恕不另行通知.
如果我做
Dim isDerivedClass1 as boolean = TypeOf(oject.ActiveItem) Is DerivedClass1
然后我得到一个编译时错误,告诉我ActiveItem永远不能是DerivedClass1类型.
我尝试了几种GetType和TypeOf的组合,但似乎无法检查这一点.我还尝试声明一个辅助DerivedClass1变量并比较它们的类型,但也没有任何运气.
有没有解决方法?
我想我可以用反射来做,但看起来真的有点矫枉过正.
编辑:
以下代码无法在vs2005 SP1中编译.
Public Class Base Public x As Integer End Class Public Class Derived1 Inherits Base Public y As Integer End Class Public Class Derived2 Inherits Base Public z As Integer End Class Public Class Unrelated Public var As Base End Class Public Class Form1 Public Sub Test(ByVal obj As Unrelated) Dim tst As Boolean tst = TypeOf obj Is Derived1 End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim obj As New Unrelated obj.var = New Derived1 Test(obj) End Sub End Class
编辑:
似乎原来的问题是我身边的错.我正在检查错误的类型(那些愚蠢的第三部分库……)
但是,我仍然试图在上面的代码中找到错误.
编辑:
再次,我的错.我正在检查Base的Unrelated类型.
我做到了这一点,工作正常:
Dim isDerivedClass1 As Boolean = TypeOf oject.ActiveItem Is DerivedClass1 Dim isDerivedClass2 As Boolean = TypeOf oject.ActiveItem Is DerivedClass2
我错过了什么吗?
编辑:我想你刚刚错过了编辑过的代码中的var属性.
Public Sub Test(ByVal obj As Unrelated) Dim tst As Boolean tst = TypeOf obj.var Is Derived1 End Sub