簡體   English   中英

如何在自定義 class 中返回屬性的值

[英]How do you return the value of a Property in a custom class

我有一個名為 Location 的自定義 vb,net class 具有多個屬性。

例子

Class = 位置

屬性 = 街道

值 =“主街”

房產 = 城市

值 = "AnyTown"

財產 = 國家

值 = “美國”

通過反射我可以得到每個屬性的名稱:

Public Function GetLocationValue(ByRef sLocation)    
Dim sTable As New ProjectSchema.Location
sTable = sLocation
For Each p As System.Reflection.PropertyInfo In sTable.GetType().GetProperties()
        If p.CanRead Then
           Console.WriteLine(p.Name)
        End If
Next
End Function

結果:

p.Name = 街道

p.Name = 城市

p.Name = 國家

如何獲取每個 p.Name 的值並返回“Main St”、“AnyTown”或“USA”

您只需要從屬性信息中獲取值:

Dim val as Object
For Each p As System.Reflection.PropertyInfo In sTable.GetType().GetProperties()
    If p.CanRead Then
       Console.WriteLine(p.Name)
       val = p.GetValue(sTable, Nothing)
       Console.WriteLine(val)
    End If
Next

其中 p 是您的 PropertyInfo object。

p.GetValue (sTable, Nothing)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM