如何遍历自定义vb.net对象的每个属性?

42

我如何遍历自定义对象中的每个属性?它不是一个集合对象,但是否有类似于此的东西可用于非集合对象?

For Each entry as String in myObject
    ' Do stuff here...
Next

我的对象中有字符串、整数和布尔型属性。

4个回答

68

通过使用反射,您可以做到这一点。在C#中它看起来像这样;

PropertyInfo[] propertyInfo = myobject.GetType().GetProperties();

增加了VB.Net的翻译:

Dim info() As PropertyInfo = myobject.GetType().GetProperties()

每个条目中的值在哪里? - Anders
有一个名为propertyInfo.GetValue()的方法。 - Ali Ersöz
在“ForEach”循环的上下文中,这是如何工作的? - tmsimont
1
@tmsimont 你需要循环遍历数组属性propertyInfo,即 For Each i in propertyInfo //做一些事情 Next - dherrin79

45

你可以使用 System.Reflection 命名空间来查询关于对象类型的信息。

For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
   If p.CanRead Then
       Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing))
   End If
Next

请注意,不建议在代码中使用该方法替代集合。反射是一种性能密集型的操作,应明智地使用。


我遇到了一个问题,它的错误是:对象引用未设置为对象的实例。 - Fame th

7

System.Reflection 是一个“重量级”的操作,我通常会先实现一种更轻量级的方法。

//C#

if (item is IEnumerable) {
    foreach (object o in item as IEnumerable) {
            //do function
    }
} else {
    foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())      {
        if (p.CanRead) {
            Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj,  null)); //possible function
        }
    }
}

'VB.Net

  If TypeOf item Is IEnumerable Then

    For Each o As Object In TryCast(item, IEnumerable)
               'Do Function
     Next
  Else
    For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
         If p.CanRead Then
               Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing))  'possible function
          End If
      Next
  End If

1

你可以使用反射... 通过反射,你可以检查类(Type)的每个成员,包括属性、方法、构造函数、字段等。

using System.Reflection;

Type type = job.GetType();
    foreach ( MemberInfo memInfo in type.GetMembers() )
       if (memInfo is PropertyInfo)
       {
            // Do Something
       }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接