我试图做的是向控制台输出任何复杂的对象,例如
伪对象:
Orderheader:
customer = ""
OrderDate = ""
requiredDate = ""
contact = ""
customerOrderNumber = ""
deliverySubcode = ""
customerName = ""
customerAddress1 = ""
customerAddress2 = ""
customerAddress3 = ""
customerAddress4 = ""
List(Of Orderlines)
Orderline:
lineNumber = ""
productCode = ""
productDescription = ""
quantity = ""
unitPrice = ""
manufacturerProductCode = ""
weight = ""
所以当它到达orderLines列表然后枚举通过这些并输出到控制台时,基本上遍历orderHeader中的每个属性,我希望能够将此用于任何类型的对象而不仅仅是上面的对象我现在的代码是:
Public Shared Sub ToFileNew(ByVal orderHeader As Object)
Dim properties = orderHeader.GetType().GetProperties()
For Each prop In properties
If IsGenericList(prop.GetValue(orderHeader, New Object() {}).GetType) Then
Dim subObjectList = prop.GetValue(orderHeader, New Object() {})
Dim subPropertys = subObjectList.GetType().GetProperties()
For Each x In subPropertys
Console.WriteLine("{0}: {1}", x.Name, x.GetValue(subObjectList, New Object() {}))
Next
Else
Console.WriteLine("{0}: {1}", prop.Name, prop.GetValue(orderHeader, New Object() {}))
End If
Next
End Sub
Public Shared Function IsGenericList(type As Type) As Boolean
If Not type Is Nothing Then
Return (From [interface] In type.GetInterfaces() Where [interface].IsGenericType).Any(Function([interface]) [interface].GetGenericTypeDefinition() = GetType(ICollection(Of )))
Else
Return False
End If
End Function
代码适用于orderHeader,但是当到达Orderline列表时,我收到以下错误:
TargetParameterCountException was unhandled
Parameter count mismatch.
此功能的目的是最终将任何对象写入CSV文件。
答案 0 :(得分:0)
对于下面有相同问题解决方案的任何人:
Public Shared Sub ToFileNew(ByVal orderHeader As Object)
Dim properties = orderHeader.GetType().GetProperties()
For Each prop In properties
If IsGenericList(prop.GetValue(orderHeader, New Object() {}).GetType) Then
Dim subObjectList = prop.GetValue(orderHeader)
For Each p In subObjectList
Dim subPropertys = p.GetType().GetProperties()
For Each x In subPropertys
Console.WriteLine("{0}: {1}", x.Name, x.GetValue(p, New Object() {}))
Next
Next
Else
Console.WriteLine("{0}: {1}", prop.Name, prop.GetValue(orderHeader, New Object() {}))
End If
Next
End Sub
Public Shared Function IsGenericList(type As Type) As Boolean
If Not type Is Nothing Then
Return (From [interface] In type.GetInterfaces() Where [interface].IsGenericType).Any(Function([interface]) [interface].GetGenericTypeDefinition() = GetType(ICollection(Of )))
Else
Return False
End If
End Function