从类中搜寻是本类集合的成员

本文介绍了一个利用.NET反射机制来查找并获取类型中所有集合属性的方法。通过实例演示了如何读取不同类型的数据结构中的集合属性,并展示了针对不同类型的集合属性进行处理的具体实现。
Author: 水如烟  

参考应用类代码辅助类代码

尝试的。

这个类蛮偏,应用范围不大。

示例代码:

Public   Class  GetSameTypeCollectionFromTypeTest
    
Private   Shared  gService  As   New  LzmTW.uSystem.uReflection.GetSameTypeCollectionFromType

    
Public   Shared   Sub  Run()
        
With  gService
            .Read(
GetType (Test))

            
Print ()
            .Clear()

            .Read(
GetType (TreeNode))
            .Read(
GetType (Control))

            
Print ()
            .Clear()

            .Read(
GetType (LzmTW.uSystem.uCollection.Node( Of   String )))
            
Print ()
        
End   With


    
End Sub

    
Private   Shared   Sub   Print ()
        
For   Each  m  As  Reflection.MemberInfo  In  gService.Result
            Console.WriteLine(
String .Concat(m.DeclaringType.FullName,  " + " , m.Name))
        
Next
    
End Sub

End Class

 

Public   Class  Test

    
Public  Items()  As  Test

    
Public   ReadOnly   Property  Nodes()  As  Test()
        
Get

        
End   Get
    
End Property
End Class

结果:

 

MainFormDemo.Test + Items
MainFormDemo.Test
+ Nodes
System.Windows.Forms.TreeNode
+ Nodes
System.Windows.Forms.Control
+ Controls
System.Windows.Forms.Control
+ DataBindings
LzmTW.uSystem.uCollection.Node`
1 [[System.String, mscorlib, Version = 2.0 . 0.0 , Culture = neutral, PublicKeyToken = b77a5c561934e089]] + Nodes

类:

Namespace  LzmTW.uSystem.uReflection

    
Public   Class  GetSameTypeCollectionFromType

        
Private  gMemberInfos  As   New  Dictionary( Of   String , Reflection.MemberInfo)
        
Private  gCollectList  As   String ()  =  { " IList " " ICollection " " IEnumerable " }

        
Public   ReadOnly   Property  Result()  As  Reflection.MemberInfo()
            
Get

                
Dim  tmp(gMemberInfos.Count  -   1 As  Reflection.MemberInfo
                gMemberInfos.Values.CopyTo(tmp, 
0 )

                
Return  tmp
            
End   Get
        
End Property

        
Public   Sub  Read( ByVal  type  As  Type,  Optional   ByVal  referBaseType  As   Boolean   =   False )

            
Me .GetFromFields(type, referBaseType)
            
Me .GetFromProperties(type, referBaseType)

        
End Sub

        
Public   Sub  Read( ByVal  item  As   Object Optional   ByVal  referBaseType  As   Boolean   =   False )
            
Dim  type  As  Type  =  item.GetType

            
Me .GetFromFields(type, referBaseType)
            
Me .GetFromProperties(type, referBaseType)

        
End Sub

        
Public   Sub  Clear()
            gMemberInfos.Clear()
        
End Sub

        
Private   Sub  Add( ByVal  memberInfo  As  Reflection.MemberInfo)

            
If   Not  gMemberInfos.ContainsKey(memberInfo.Name)  Then
                gMemberInfos.Add(memberInfo.Name, memberInfo)
            
End   If

        
End Sub

        
Private   Sub  AddByInterfaceType( ByVal  type  As  Type,  ByVal  memberInfo  As  Reflection.MemberInfo,  ByVal  PropertyTypeProperty  As  Reflection.PropertyInfo,  ByVal  referBaseType  As   Boolean )
            
If  referBaseType  Then
                
If  PropertyTypeProperty.PropertyType  Is  type.BaseType  Then
                    Add(memberInfo)
                
End   If
            
Else
                
If  PropertyTypeProperty.PropertyType  Is  type  Then
                    Add(memberInfo)
                
End   If
            
End   If
        
End Sub

        
Private   Sub  AddByArray( ByVal  type  As  Type,  ByVal  TypePropertyInfo  As  Reflection.PropertyInfo,  ByVal  TypePropertyInfoGetMemthodInfo  As  Reflection.MethodInfo,  ByVal  referBaseType  As   Boolean )
            
If  TypePropertyInfoGetMemthodInfo  IsNot   Nothing   Then
                
If  referBaseType  Then
                    
If  TypePropertyInfoGetMemthodInfo.ReturnType.Name.Equals(type.BaseType.Name  &   " [] " Then
                        Add(TypePropertyInfo)
                    
End   If
                
Else
                    
If  TypePropertyInfoGetMemthodInfo.ReturnType.Name.Equals(type.Name  &   " [] " Then
                        Add(TypePropertyInfo)
                    
End   If
                
End   If
            
End   If
        
End Sub

        
Private   Sub  AddByArray( ByVal  type  As  Type,  ByVal  TypeFieldInfo  As  Reflection.FieldInfo,  ByVal  referBaseType  As   Boolean )

            
If  referBaseType  Then
                
If  TypeFieldInfo.FieldType.Name.Equals(type.BaseType.Name  &   " [] " Then
                    Add(TypeFieldInfo)
                
End   If
            
Else
                
If  TypeFieldInfo.FieldType.Name.Equals(type.Name  &   " [] " Then
                    Add(TypeFieldInfo)
                
End   If
            
End   If

        
End Sub

        
Private   Sub  GetFromFields( ByVal  t  As  Type,  Optional   ByVal  referBaseType  As   Boolean   =   False )

            
For   Each  TypeFieldInfo  As  Reflection.FieldInfo  In  t.GetFields

                
If  TypeFieldInfo.FieldType.IsArray  Then

                    AddByArray(t, TypeFieldInfo, referBaseType)
                
End   If

            
Next

        
End Sub

        
Private   Sub  GetFromProperties( ByVal  t  As  Type,  Optional   ByVal  referBaseType  As   Boolean   =   False )


            
For   Each  TypePropertyInfo  As  Reflection.PropertyInfo  In  t.GetProperties

                
If  TypePropertyInfo.PropertyType.IsArray  Then

                    
Dim  TypePropertyInfoGetMemthodInfo  As  Reflection.MethodInfo  =  TypePropertyInfo.GetGetMethod( False )
                    AddByArray(t, TypePropertyInfo, TypePropertyInfoGetMemthodInfo, referBaseType)

                
Else
                    
For   Each  PropertyInterfaceType  As  Type  In  TypePropertyInfo.PropertyType.GetInterfaces

                        
If  Array.IndexOf(gCollectList, PropertyInterfaceType.Name)  <>   - 1   Then

                            
For   Each  PropertyTypeProperty  As  Reflection.PropertyInfo  In  TypePropertyInfo.PropertyType.GetProperties

                                AddByInterfaceType(t, TypePropertyInfo, PropertyTypeProperty, referBaseType)

                            
Next

                        
End   If

                    
Next
                
End   If

            
Next

        
End Sub

    
End Class

End Namespace

测试一下Framewoks,这种情形还真不多:

 

Public   Class  GetSameTypeCollectionFromTypeTest
    
Private   Shared  gService  As   New  LzmTW.uSystem.uReflection.GetSameTypeCollectionFromType

    
Public   Shared   Sub  Run()
        CheckFrameworks()
    
End Sub

    
Private   Shared   Sub   Print ()
        
For   Each  m  As  Reflection.MemberInfo  In  gService.Result
            Console.WriteLine(
String .Concat(m.DeclaringType.FullName,  " + " , m.Name))
        
Next
    
End Sub

    
Private   Shared   Sub  CheckFrameworks()

        
Dim  mAllDllFiles  As  ArrayList  =  GetFrameworksDLLFileList()
        
For   Each  f  As   String   In  mAllDllFiles
            
Try
                
Dim  mAssembly  As   Assembly   =   Assembly .LoadFrom(f)

                
For   Each  mModule  As  [ Module In  mAssembly.GetModules

                    
For   Each  mType  As  Type  In  mModule.GetTypes
                        gService.Clear()
                        gService.Read(mType)
                        
Print ()
                    
Next
                
Next
            
Catch  ex  As  Exception
            
End   Try
        
Next

    
End Sub

    
Private   Shared   Function  GetFrameworksDLLFileList()  As  ArrayList
        
Dim  mList  As   New  ArrayList
        
Dim  mFrameworksPath  As   String   =   Nothing

        
Dim  tmpAssembly  As  System.Reflection.Assembly  =   GetType ( Object ).Assembly
        mFrameworksPath 
=  IO.Path.GetDirectoryName(tmpAssembly.Location)

        
Try

            
If  Directory.Exists(mFrameworksPath)  Then
                
Dim  dllFiles  As   String ()  =  Directory.GetFiles(mFrameworksPath,  " *.dll " )

                
For  i  As   Integer   =   0   To  dllFiles.Length  -   1
                    mList.Add(dllFiles(i))
                
Next  i
            
End   If

        
Catch  Ex  As  Exception
        
End   Try

        
Return  mList
    
End Function
End Class

结果:

Microsoft.Build.Tasks.Deployment.Bootstrapper.BootstrapperBuilder + GraphNode + Edges
System.Type
+ EmptyTypes
System.Reflection.CustomAttributeEncodedArgument
+ ArrayValue
System.Configuration.ConfigurationSectionGroup
+ SectionGroups
System.Configuration.Install.Installer
+ Installers
System.Diagnostics.SerializableRegistryKey
+ Keys
System.Data.DataRowView
+ DataView
System.Data.DataSet
+ DefaultViewManager
System.Data.DataTable
+ DefaultView
System.Xml.Xsl.XmlQueryType
+ Prime
System.Xml.ListBase`
1 [[System.Xml.Xsl.XmlQueryType, System.Data.SqlXml, Version = 2.0 . 0.0 , Culture = neutral, PublicKeyToken = b77a5c561934e089]] + Item
System.Xml.Xsl.Qil.QilNode
+ Item
System.Xml.Xsl.Xslt.Stylesheet
+ Imports
System.Xml.Xsl.Xslt.XslNode
+ Content
System.Web.UI.Design.DataBindingsDialog
+ FormatItem + DefaultFormats
System.Web.UI.Design.DataBindingsDialog
+ FormatItem + DateTimeFormats
System.Web.UI.Design.DataBindingsDialog
+ FormatItem + NumericFormats
System.Web.UI.Design.DataBindingsDialog
+ FormatItem + DecimalFormats
System.DirectoryServices.ActiveDirectory.ActiveDirectorySchemaClass
+ PossibleSuperiors
System.DirectoryServices.ActiveDirectory.ActiveDirectorySchemaClass
+ PossibleInferiors
System.DirectoryServices.ActiveDirectory.ActiveDirectorySchemaClass
+ AuxiliaryClasses
System.DirectoryServices.ActiveDirectory.ActiveDirectorySite
+ AdjacentSites
System.DirectoryServices.ActiveDirectory.Domain
+ Children
System.CodeDom.CodeTypeReference
+ TypeArguments
System.ComponentModel.Design.DesignerOptionService
+ DesignerOptionCollection + Parent
System.ComponentModel.Design.DesignerOptionService
+ DesignerOptionCollection + Item
System.Collections.Generic.LinkedListNode`
1 + List
System.Drawing.FontFamily
+ Families
System.Messaging.DefaultPropertiesToSend
+ AdministrationQueue
System.Messaging.DefaultPropertiesToSend
+ ResponseQueue
System.Messaging.DefaultPropertiesToSend
+ TransactionStatusQueue
System.Security.Cryptography.Pkcs.SignerInfo
+ CounterSignerInfos
System.ServiceProcess.ServiceController
+ DependentServices
System.ServiceProcess.ServiceController
+ ServicesDependedOn
System.Web.HttpApplicationState
+ Contents
System.Web.SiteMapNode
+ ChildNodes
System.Web.SessionState.HttpSessionState
+ Contents
System.Web.UI.Control
+ Controls
System.Web.UI.WebControls.MenuItem
+ ChildItems
System.Web.UI.WebControls.TreeNode
+ ChildNodes
System.Web.Services.Description.MimeTextMatch
+ Matches
System.Web.Services.Description.ServiceDescription
+ ServiceDescriptions
System.Windows.Forms.IBindableComponent
+ DataBindings
System.Windows.Forms.Control
+ Controls
System.Windows.Forms.Control
+ DataBindings
System.Windows.Forms.Control
+ ImeModeConversion + ImeModeConversionBits
System.Windows.Forms.Form
+ MdiChildren
System.Windows.Forms.Form
+ OwnedForms
System.Windows.Forms.GridItem
+ GridItems
System.Windows.Forms.HtmlElement
+ All
System.Windows.Forms.HtmlElement
+ Children
System.Windows.Forms.HtmlWindow
+ Frames
System.Windows.Forms.InputLanguage
+ InstalledInputLanguages
System.Windows.Forms.Menu
+ MenuItems
System.Windows.Forms.Screen
+ AllScreens
System.Windows.Forms.TableLayoutPanel
+ Controls
System.Windows.Forms.TreeNode
+ Nodes
System.Xml.XmlNode
+ ParentNode
System.Xml.XmlNode
+ ChildNodes
System.Xml.XmlNode
+ PreviousSibling
System.Xml.XmlNode
+ NextSibling
System.Xml.XmlNode
+ OwnerDocument
System.Xml.XmlNode
+ FirstChild
System.Xml.XmlNode
+ LastChild
System.Xml.XmlNode
+ Item
System.Xml.XmlNode
+ Attributes
System.Xml.XmlAttributeCollection
+ ItemOf
System.Xml.XmlNodeList
+ ItemOf
System.Xml.XmlDocument
+ ParentNode
System.Xml.XmlDocument
+ DocumentType
System.Xml.XmlDocument
+ DocumentElement
System.Xml.XmlDocument
+ OwnerDocument
System.Xml.XmlNode
+ PreviousSibling
System.Xml.XmlNode
+ NextSibling
System.Xml.XmlNode
+ FirstChild
System.Xml.XmlNode
+ LastChild
System.Xml.XmlNode
+ Item
System.Xml.XmlNode
+ OwnerDocument
System.Xml.XmlElement
+ ParentNode
System.Xml.XmlElement
+ OwnerDocument
System.Xml.XmlElement
+ NextSibling
System.Xml.XmlLinkedNode
+ PreviousSibling
System.Xml.XmlNode
+ FirstChild
System.Xml.XmlNode
+ LastChild
System.Xml.XmlNode
+ Item
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值