簡體   English   中英

迭代類屬性

[英]Iterate through class properties

我有一個名為ticket的VB.NET類,它有幾個'field'類型的公共屬性。 我希望有一種方法可以遍歷所有這些屬性(每個屬性都有一個),並對每個屬性執行特定任務。 我認為最好的方法可能是創建一個列表(Of field)並用該類的'field'屬性填充列表。 我不知道該怎么做是動態地將屬性放入列表中,這樣如果我以后添加屬性,我不必手動將它們輸入列表。 有關如何做到這一點的任何想法? 我嘗試搜索並找到了一些使用反射的例子,但我只能弄清楚如何得到屬性的名稱而不是屬性本身。

這是一個類的示例:

Public Class ticket
    Public Property location As New field
    Public Property user As New field
    Public Property callType As New field
    Public Property dateOfCall As New field
    Public Property tech As New field
    Public Property description As New field

    Public Property myFields As New List(Of field)

'What if field had a property of value and I wanted to increment all of the fields    in this class by one

Public Sub plusOne()
    For Each x As field In myFields()
        x.value += 1
    Next
End Sub

End Class

您想使用Reflection ,這意味着檢查程序集中的類型。 您可以通過System.Reflection命名空間執行此操作。

有關VB.Net中反射的示例,請參閱msdn雜志上的以下文章: http//msdn.microsoft.com/en-us/magazine/cc163750.aspx

在該文章中迭代類型成員的示例如下:

Dim t As Type = GetType(AcmeCorp.BusinessLogic.Customer)
For Each member As MemberInfo In t.GetMembers
  Console.WriteLine(member.Name)
Next

再次作為前面的答案 - 你會使用反射。 要作為示例調用AddList(Of T)我會這樣做。

Public Class Test
  Public Property SomeList As List(Of String)
End Class

然后使用以下代碼調用List(Of String)上的add

Dim pi As PropertyInfo = GetType(Test).GetProperty("SomeList")
Dim mi As MethodInfo = GetType(List(Of String)).GetMethod("Add")
Dim t As New Test()
t.SomeList = New List(Of String)
mi.Invoke(pi.GetValue(t, Nothing), New Object() {"Added through reflection"})

如前所述,您需要使用System.Reflection來獲取類的屬性。 然后檢查屬性是否是您想要的類型。

希望這應該給你你想要的。 如果運行代碼,您將看到它只接受指定類型的屬性。 如果要擁有所有屬性,請刪除for each循環中的where語句。

Imports System.Reflection

Module Module1

Sub Main()

    ' Create a list to hold your properties
    Dim myList As New List(Of MyProperty)

    ' check each property for its type using the where statement below. Change integer to "Field" in your case
    For Each el In GetType(Test).GetProperties.Where(Function(p) p.PropertyType = GetType(Integer))
        ' add each matching property to the list
        myList.Add(New MyProperty With {.Name = el.Name, .GetMethod = el.GetGetMethod(), .SetMethod = el.GetSetMethod()})
        Console.WriteLine(el.Name & " has been added to myList")
    Next

    Console.Read()
End Sub

Public Class MyProperty
    Public Property Name As String
    Public Property GetMethod As MethodInfo
    Public Property SetMethod As MethodInfo
End Class

Public Class Test
    Private var1 As String
    Private var2 As String
    Private var3 As String
    Private var4 As String

    Public Property myInt1 As Integer
    Public Property myInt2 As Integer
    Public Property myInt3 As Integer
    Public Property myInt4 As Integer
End Class
End Module

希望有所幫助

暫無
暫無

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

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