【发布时间】:2013-12-28 12:53:45
【问题描述】:
我有一组类,它们的属性上有数据注释。其中一些类属性是原始类型(原始也是指字符串、双精度、日期时间等类型),而另一些是自定义类型的属性。
我希望能够遍历类的属性和嵌套对象的属性,并提取每个属性的属性。如果所考虑的类只有一个自定义类型的属性,我已经玩过反射并且我的代码工作正常。 但是,当一个类有多个自定义类型的属性并且每个属性都有其他自定义类型时,我完全不知道如何跟踪已经访问过的对象/属性。
这就是我到目前为止所取得的成就。我在论坛上看到了很多例子,但是它们都有一个简单的嵌套类,每个类最多有一个自定义类型。 以下是我正在尝试完成的示例:
Public Class Claim
<Required()>
<StringLength(5)>
Public Property ClaimNumber As String
<Required()>
Public Property Patient As Patient
<Required()>
Public Property Invoice As Invoice
End Class
Public Class Patient
<Required()>
<StringLength(5)>
Public Property MedicareNumber As String
<Required()>
Public Property Name As String
<Required()>
Public Property Address As Address
End Class
Public Class Address
Public Property Suburb As String
Public Property City As String
End Class
Public Class Invoice
<Required()>
Public Property InvoiceNumber As String
<Required()>
Public Property Procedure As String
End Class
Public Shared Function Validate(ByVal ObjectToValidate As Object) As List(Of String)
Dim ErrorList As New List(Of String)
If ObjectToValidate IsNot Nothing Then
Dim Properties() As PropertyInfo = ObjectToValidate.GetType().GetProperties()
For Each ClassProperty As PropertyInfo In Properties
Select Case ClassProperty.PropertyType.FullName.Split(".")(0)
Case "System"
Dim attributes() As ValidationAttribute = ClassProperty.GetCustomAttributes(GetType(ValidationAttribute), False)
For Each Attribute As ValidationAttribute In attributes
If Not Attribute.IsValid(ClassProperty.GetValue(ObjectToValidate, Nothing)) Then
ErrorList.Add("Attribute Error Message")
End If
Next
Case Else
Validate(ClassProperty.GetValue(ObjectToValidate, Nothing))
**** ‘At this point I need a mechanism to keep track of the parent of ClassProperty and also mark ClassProperty as visited, so that I am able to iterate through the other properties of the parent (ObjectToValidate), without revisiting ClassProperty again.**
End Select
Next
End If
Return Nothing
End Function
【问题讨论】:
标签: vb.net object reflection recursion