How to iterate through each property of a custom vb.net object?

后端 未结 4 1814
囚心锁ツ
囚心锁ツ 2020-12-07 21:25

How can I go through each of the properties in my custom object? It is not a collection object, but is there something like this for non-collection objects?

         


        
4条回答
  •  悲哀的现实
    2020-12-07 21:35

    System.Reflection is "heavy-weight", i always implement a lighter method first..

    //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
    

提交回复
热议问题