小编典典

如何遍历一个类的所有属性?

all

我有一堂课。

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

阅读 79

收藏
2022-08-24

共1个答案

小编典典

使用反射:

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()来获取属性的值。

2022-08-24