我有课。
公共类Foo
私人_Name作为字符串
公共属性Name()作为字符串
得到
返回_Name
最终获取
设置(BYVAL值作为字符串)
_Name =价值
结束设定
高端物业
私人_Age作为字符串
公共财产年龄()作为字符串
得到
返回_Age
最终获取
设置(BYVAL值作为字符串)
_Age =价值
结束设定
高端物业
私人_ContactNumber作为字符串
公共财产ContactNumber()作为字符串
得到
返回_ContactNumber
最终获取
设置(BYVAL值作为字符串)
_ContactNumber =价值
结束设定
高端物业
末级
欲通过上述类的属性循环。 例如;
公用Sub DisplayAll(BYVAL Someobject为Foo)
对于每个_property作为东西Someobject.Properties
Console.WriteLine(_Property.Name&安培;=&安培; _Property.value)
下一个
结束小组
解决方案
使用反射:
输入型= obj.GetType();
的PropertyInfo []属性= type.GetProperties();
的foreach(在属性的PropertyInfo财产)
{
Console.WriteLine(姓名:+ property.Name +,值:+ property.GetValue(OBJ,NULL));
}
编辑:您还可以指定的BindingFlags值 type.GetProperties()
:
的BindingFlags标志= BindingFlags.Public | BindingFlags.Instance;
的PropertyInfo []属性= type.GetProperties(标志);
这将返回的属性限制在公共实例属性(不包括静态性能,保护性能,等等)。
您不必指定 BindingFlags.GetProperty
,您使用时调用 type.InvokeMember()
得到一个属性的值
I have a class.
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
I want to loop through the properties of the above class. eg;
Public Sub DisplayAll(ByVal Someobject As Foo)
For Each _Property As something In Someobject.Properties
Console.WriteLine(_Property.Name & "=" & _Property.value)
Next
End Sub
解决方案
Use Reflection:
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}
Edit: You can also specify a BindingFlags value to type.GetProperties()
:
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);
That will restrict the returned properties to public instance properties (excluding static properties, protected properties, etc).
You don't need to specify BindingFlags.GetProperty
, you use that when calling type.InvokeMember()
to get the value of a property.