gpt4 book ai didi

.net - 如何循环遍历一个类的所有属性?

转载 作者:行者123 更新时间:2023-12-02 11:57:57 26 4
gpt4 key购买 nike

我有课。

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”条目

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

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

这会将返回的属性限制为公共(public)实例属性(不包括静态属性、 protected 属性等)。

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

关于.net - 如何循环遍历一个类的所有属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/531384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com