41

如何查看自定义对象中的每个属性?它不是一个集合对象,但是对于非集合对象有这样的东西吗?

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

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

4

4 回答 4

67

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

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

添加了 VB.Net 翻译:

Dim info() As PropertyInfo = myobject.GetType().GetProperties()
于 2008-11-24T15:15:16.540 回答
44

您可以使用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

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

于 2008-11-24T15:22:08.350 回答
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
于 2011-11-17T12:35:31.580 回答
1

您可以使用反射...使用反射,您可以检查类的每个成员(类型)、属性、方法、构造函数、字段等。

using System.Reflection;

Type type = job.GetType();
    foreach ( MemberInfo memInfo in type.GetMembers() )
       if (memInfo is PropertyInfo)
       {
            // Do Something
       }
于 2008-11-24T15:16:49.297 回答