如何解决如何遍历一个类的所有属性??
使用反射:
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()
来获取属性的值。
解决方法
我有一堂课。
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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。