通过类属性迭代(Iterate through class properties)

2019-08-02 13:05发布

我有一个VB.NET类叫做票有型“场”的几个公共属性。 我想有一个办法,我可以通过所有这些属性(有一个)的迭代,并在他们每个人的执行特定的任务。 我想,也许最好的方法是创建一个列表(场),并与类的“场”的属性填充列表。 我不知道该怎么做的就是属性到列表中动态的,因此如果我在将来添加的属性,我没有给他们手动键入到列表中。 我如何可能做到这一点有什么想法? 我试图寻找和发现使用反射的一些例子,但我只能找出如何在财产的名称,而不是物业本身得到。

这里是一个类的一个例子:

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

Answer 1:

你想用的反思 ,这只是意味着在装配检查类型。 您可以通过做到这一点的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


Answer 2:

再次为以前的答案 - 你会使用反射。 要调用作为一个例子AddList(Of T)我会做到这一点。

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

然后使用下面的代码来调用上添加一个List(Of String)

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"})


Answer 3:

由于以前的答案说,你需要使用的System.Reflection来获取类的属性。 然后检查属性是你想要的类型。

这应该可以给你想要的东西。 如果您运行的代码,你会看到,只需要指定类型的属性。 如果你想拥有的所有属性,去掉其中的语句在每个循环。

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

希望帮助



文章来源: Iterate through class properties