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

前端之家收集整理的这篇文章主要介绍了.net – 如何遍历一个类的所有属性?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个类。
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));
}

编辑:您还可以指定一个BindingFlags值为type.GetProperties():

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

这将把返回的属性限制为公共实例属性(不包括静态属性,受保护属性等)。

你不需要指定BindingFlags.GetProperty,在调用type.InvokeMember()时使用它来获取属性的值。

原文链接:https://www.f2er.com/vb/256678.html

猜你在找的VB相关文章