无法遍历自定义对象的每个属性

时间:2019-02-28 17:22:54

标签: vb.net

我上了这个课:

Public Class clsServCasam
    Public ID As Long
    Public CANT As Decimal
    Public PRICE As Decimal
End Class

我创建该类型的变量并从API结果中获取对象:

Dim myObj As clsServCasam()
Dim rsp As HttpWebResponse = CType(rq.GetResponse(), HttpWebResponse)
If rsp.StatusCode = HttpStatusCode.OK Then
    Using sr = New StreamReader(rsp.GetResponseStream())
        myObj = JsonConvert.DeserializeObject(Of clsServCasam())(sr.ReadToEnd())
    End Using

然后我尝试从对象中获取字段名称:

For Each p As System.Reflection.PropertyInfo In myObj.GetType().GetProperties()
    Debug.Print(p.Name, p.GetValue(myObj, Nothing))
Next

但是,我得到的不是类字段(ID,PRICE等):

- Length
- LongLength
- Rank

更新

正如Steven Doggart指出的那样,上述循环将不起作用,因为它查找的是属性而不是字段。因此,我尝试将循环更改为此:

For Each p As FieldInfo In myObj.GetType.GetFields()
    Debug.Print(p.Name)
Next

但是现在我什么都没有得到。

1 个答案:

答案 0 :(得分:2)

在您的代码中,myObj未声明为clsServCasam。相反,它被声明为clsServCasam(),这意味着它是clsServCasam对象的数组。因此,当您使用反射来遍历其属性时,您将获得数组的属性,而不是实际的clsServCasam类型。

例如,这将更像您期望的那样工作:

For Each item As clsServCasam in myObj
    For Each p As PropertyInfo In item.GetType().GetProperties()
        Debug.Print(p.Name, p.GetValue(item, Nothing))
    Next
Next

但是,我认为您会发现仍然无法使用,因为它会遍历属性而不是字段。在clsServCasam类的定义中,所有成员都是字段而不是属性,因此它仅有的属性是从Object继承的属性。您将需要使用GetFields遍历字段,如下所示:

For Each item As clsServCasam in myObj
    For Each f As FieldInfo In item.GetType().GetFields()
        Debug.Print(f.Name, f.GetValue(item))
    Next
Next

或者您需要将它们更改为属性:

Public Class clsServCasam
    Public Property ID As Long
    Public Property CANT As Decimal
    Public Property PRICE As Decimal
End Class

或者,如果您使用的VB编译器的旧版本不支持自动属性:

Public Class clsServCasam
    Public Property ID As Long
        Get
            Return _id
        End Get
        Set(value As Long)
            _id = value
        End Set
    End Property

    Public Property CANT As Decimal
        Get
            Return _cant
        End Get
        Set(value As Decimal)
            _cant = value
        End Set
    End Property

    Public Property PRICE As Decimal
        Get
            Return _price
        End Get
        Set(value As Decimal)
            _price = value
        End Set
    End Property

    Private _id As Long
    Private _cant As Decimal
    Private _price As Decimal
End Class