遍历类属性 [英] Iterate through class properties

查看:61
本文介绍了遍历类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Ticket的VB.NET类,该类具有 field类型的几个公共属性。我想有一种方法可以遍历所有这些属性(每个属性一个),并对每个属性执行特定的任务。我认为最好的方法可能是创建一个列表(字段),然后用该类的字段属性填充列表。我不知道该怎么做,是将属性动态地添加到列表中,这样以后再添加属性时,就不必手动将其输入列表中。关于如何执行此操作有任何想法吗?我尝试搜索并找到了一些使用反射的示例,但我只能弄清楚如何获得属性的名称,而不是属性本身。



这里是一个类的示例:

 公共类票
公共财产位置为新字段
公共财产用户为新字段
公共属性callType为新字段
公共属性dateOfCall为新字段
公共属性技术为新字段
公共属性描述为新字段

公共属性myFields作为新列表(字段)

'如果字段具有值属性,我想将此类中的所有字段增加一个

Sub plusOne()
每个myAss()中的x As字段
x.value + = 1
下一个
End Sub

End Class


解决方案

您要使用反射,这仅意味着检查装配中的类型。您可以通过 System.Reflection 命名空间来实现。 p>

有关在VB.Net中进行反射的示例,请参见msdn杂志上的以下文章:
http://msdn.microsoft.com/en-us/magazine/cc163750.aspx



该文章中的类型成员迭代的示例如下:

  Dim t As Type = GetType (AcmeCorp.BusinessLogic.Customer)
每个成员作为t.GetMembers
Console.WriteLine(member.Name)中的MemberInfo在每个


I have a VB.NET class called ticket that has several public properties of type 'field'. I would like to have a way that I can iterate through all of these properties (with a for each) and perform a specific task on each of them. I thought that maybe the best way was to create a list(Of field) and fill the list with the 'field' properties of that class. What I don't know how to do is get the properties into the list dynamically so that if I add properties in the future I don't have to type them into the list manually. Any thoughts on how I might do this? I tried searching for and found some examples of using reflection but I could only figure out how to get at the name of the property and not the property itself.

Here is an example of a class:

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

解决方案

You want to use Reflection, which just means inspecting the types in an assembly. You can do this via the System.Reflection namespace.

See the following article on the msdn magazine for examples of reflection in VB.Net: http://msdn.microsoft.com/en-us/magazine/cc163750.aspx

An example of iterating over the members of a type in that article is as follows:

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

这篇关于遍历类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆