Dot-Net

如何遍歷一個類的所有屬性?

  • February 10, 2009

我有一堂課。

Public Class Foo
   Private _Name As String
   Public Property Name() As String
       Get
           Return _Name
       End Get
       Set(ByVal value As String)
           _Name = value
       End Set
   End Property

   Private _Age As String
   Public Property Age() As String
       Get
           Return _Age
       End Get
       Set(ByVal value As String)
           _Age = value
       End Set
   End Property

   Private _ContactNumber As String
   Public Property ContactNumber() As String
       Get
           Return _ContactNumber
       End Get
       Set(ByVal value As String)
           _ContactNumber = value
       End Set
   End Property


End Class

我想遍歷上述類的屬性。例如;

Public Sub DisplayAll(ByVal Someobject As Foo)
   For Each _Property As something In Someobject.Properties
       Console.WriteLine(_Property.Name & "=" & _Property.value)
   Next
End Sub

使用反射:

Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
   Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}

對於 Excel - 必須添加哪些工具/參考項才能訪問 BindingFlags,因為列表中沒有“System.Reflection”條目

編輯:您還可以將 BindingFlags 值指定為type.GetProperties()

BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);

這會將返回的屬性限制為公共實例屬性(不包括靜態屬性、受保護的屬性等)。

您不需要指定BindingFlags.GetProperty,在呼叫時使用它type.InvokeMember()來獲取屬性的值。

引用自:https://stackoverflow.com/questions/531384