简体   繁体   English

VB .NET DirectCast和类型反射

[英]VB .NET DirectCast and Type Reflection

The application that I am working on has a generic Parent Form called RSChild, that is used to perform some operations depending on whether or not the control that is contained within it is in a MdiTabManager or inside of its own modal form. 我正在处理的应用程序有一个通用的父窗体,称为RSChild,用于执行某些操作,具体取决于其中包含的控件是处于MdiTabManager中还是位于其自身的模式窗体中。 Then the actual User Controls contained within Inherit from a Interface Called ObjectEdit (Objects that we allow to be edited). 然后,从称为ObjectEdit的接口的Inherit中继承了实际的用户控件(我们允许对其进行编辑的对象)。 At a point in my code I am doing this. 在我的代码中,我正在这样做。

Public Function doesTabExist(ByVal id As Integer, ByVal recordType As Enums.eRecordType) As Boolean
        Dim alikePages As Object = (From tabs In DirectCast(Control.FromHandle(MainForm.SharedHandle), MainForm).XtraTabbedMdiManager1.Pages Where DirectCast(tabs.MdiChild, RSChild).RSObject.RecordType = recordType Select tabs)
        For Each page As DevExpress.XtraTabbedMdi.XtraMdiTabPage In alikePages
            Select Case recordType
                Case Enums.eRecordType.Doctor
                    If id = DirectCast(castTabPageToRSChild(page).RSObject, UI.Doctor).ID Then
                        pageToActive(page)
                        Return True
                    End If
'rest of the cases so the case block is repeated 10 times'

End Function

And my castTabPageToRSChild(page) is a lambda function as Such 我的castTabPageToRSChild(page)是一个lambda函数,例如

 Dim castTabPageToRSChild As Func(Of DevExpress.XtraTabbedMdi.XtraMdiTabPage, RSChild) = Function(page) DirectCast(page.MdiChild, RSChild)

So my Question is, I have about 10 case statements, all because I can't seem to find a way to use reflection to get the underlying Type of the RSObject Object. 所以我的问题是,我有大约10个case语句,都是因为我似乎找不到找到使用反射来获取RSObject对象的基础类型的方法。 So I have the whole If block repeated over and over. 所以我要反复重复整个If块。 I tried doing castTabPageToRSChild(page)RSObject.GetType and using that in the DirectCast and I also tried creating another object that was separate from that and doing the same thing. 我尝试执行castTabPageToRSChild(page)RSObject.GetType并在DirectCast使用它,并且还尝试创建另一个与此对象分离的对象,并执行相同的操作。

My code works as intended I'm just trying to see if there is a manner in which I didn't have a lot of replicated code. 我的代码按预期工作,我只是想看看是否有一种方式可以避免大量的重复代码。 My vision would be to do something like 我的愿景是做类似的事情

For Each page As XtraMdiTabPage In alikePages
    If id = DirectCast(castTabPageToRSchild(page).RSObject, castTabPageToRSChild(page).RSObject.GetType).Id Then Return True
Next

However I have a feeling this is not possible due to the behavior of DirectCast . 但是由于DirectCast的行为,我感觉这是不可能的。

Use TryCast instead. 改用TryCast。 It returns Nothing if the object is not of the expected type. 如果对象不是预期的类型,则返回Nothing。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM