如果我有一个复杂的结构,其中包含简单和复杂类型的属性,我如何迭代这个结构的所有属性和任何非简单类型的子属性?
我有一个名为file的复杂类型,它包含许多字符串属性,还有一些是包含类似结构的其他复杂类型,最终整个结构分解为字符串.
目前我的代码看起来像这样:
Dim file As New File
Dim props() As PropertyInfo = file.GetType.GetProperties()
_propList = New CheckBoxList
For Each prop As PropertyInfo In props
_propList.Items.Add(prop.Name)
Next
Run Code Online (Sandbox Code Playgroud)
此代码加载我的checkboxlist,其中包含我的文件类型的子属性的所有名称.我真正想要的是一个列表,其中包含构成文件的所有复杂类型的字符串类型的所有属性名称.
我很反思,所以我不知道如何处理这个问题.
感谢您的建议到目前为止.我使用类似于提供的C#代码的Visual Basic代码创建了一个递归函数.代码现在看起来像这样:
Private Function GetStringPropertyNames(ByVal Type As System.Type) As List(Of String)
Dim props() As PropertyInfo = Type.GetProperties
Dim propList As New List(Of String)
For Each prop As PropertyInfo In props
If prop.Name <> "Chronology" And _
prop.Name <> "Documents" And _
prop.Name <> "Milestones" And _
prop.Name <> "DiaryEntries" And _
prop.Name <> "FileLoadSuccesful" And _
prop.Name <> "FileLoadError" Then
Dim boo As Boolean = False
Dim bootype As Type = boo.GetType
Dim dec As Decimal
Dim decType As Type = dec.GetType
If prop.PropertyType Is "".GetType Or _
prop.PropertyType Is Now.GetType Or _
prop.PropertyType Is bootype Or _
prop.PropertyType Is decType Then
propList.Add(prop.Name)
Else
Dim listChildPropertyStrings As List(Of String) = GetStringPropertyNames(prop.PropertyType)
For Each strProp As String In listChildPropertyStrings
propList.Add(prop.Name & ": " & strProp)
Next
End If
End If
Next
Return propList
End Function
Run Code Online (Sandbox Code Playgroud)
这是有效的,但它很难看,我对某些块感到满意,特别是类型比较,以确定这是一个日期,字符串,小数或布尔值,这是我想要的潜在的低级别类型.
在C#中,似乎这些类型比较更容易,但我似乎必须创建给定类型的实例才能使用GetType返回其类型.
还有其他方法可以清除此代码吗?
你走在正确的轨道上,查尔斯,只记得:"递归".
正如你抱怨VB.NET中类型比较的"丑陋",只要记住你也可以将类型比较为:
If TypeOf obj Is GetType(DataType) Then
Run Code Online (Sandbox Code Playgroud)
就像你在C#中做的那样.