授業があります。
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
ベストアンサー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 の場合 - リストに「System.Reflection」エントリがないため、BindingFlags にアクセスするために追加する必要があるツール/参照項目は何ですか?
編集: BindingFlags 値を次のように指定することもできますtype.GetProperties()
:
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);
これにより、返されるプロパティはパブリック インスタンス プロパティに制限されます (静的プロパティ、保護されたプロパティなどは除く)。
を指定する必要はありません。プロパティの値を取得するためにBindingFlags.GetProperty
呼び出すときに使用します。type.InvokeMember()