【问题标题】:How to iterate through each property of a custom vb.net object?如何遍历自定义 vb.net 对象的每个属性?
【发布时间】:2010-09-23 18:53:00
【问题描述】:

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

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

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

【问题讨论】:

    标签: asp.net vb.net properties


    【解决方案1】:

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

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

    添加了VB.Net翻译:

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

    【讨论】:

    • 每个条目中的值在哪里?
    • 有个方法叫propertyInfo.GetValue()。
    • 这在For Each 循环的上下文中是如何工作的?
    • @tmsimont 您将循环遍历数组 propertyInfo 即。 For Each i in propertyInfo //Do stuff Next
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 我遇到了问题。这是错误:对象引用未设置为对象的实例。
      【解决方案4】:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-12
        • 1970-01-01
        • 1970-01-01
        • 2021-02-15
        • 2012-01-08
        • 1970-01-01
        相关资源
        最近更新 更多