我如何遍历自定义对象中的每个属性?它不是一个集合对象,但是否有类似于此的东西可用于非集合对象?
For Each entry as String in myObject
' Do stuff here...
Next
我的对象中有字符串、整数和布尔型属性。
我如何遍历自定义对象中的每个属性?它不是一个集合对象,但是否有类似于此的东西可用于非集合对象?
For Each entry as String in myObject
' Do stuff here...
Next
我的对象中有字符串、整数和布尔型属性。
通过使用反射,您可以做到这一点。在C#中它看起来像这样;
PropertyInfo[] propertyInfo = myobject.GetType().GetProperties();
增加了VB.Net的翻译:
Dim info() As PropertyInfo = myobject.GetType().GetProperties()
你可以使用 System.Reflection 命名空间来查询关于对象类型的信息。
For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
If p.CanRead Then
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing))
End If
Next
请注意,不建议在代码中使用该方法替代集合。反射是一种性能密集型的操作,应明智地使用。
System.Reflection 是一个“重量级”的操作,我通常会先实现一种更轻量级的方法。
//C#
if (item is IEnumerable) {
foreach (object o in item as IEnumerable) {
//do function
}
} else {
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties()) {
if (p.CanRead) {
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, null)); //possible function
}
}
}
'VB.Net
If TypeOf item Is IEnumerable Then
For Each o As Object In TryCast(item, IEnumerable)
'Do Function
Next
Else
For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
If p.CanRead Then
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing)) 'possible function
End If
Next
End If
你可以使用反射... 通过反射,你可以检查类(Type)的每个成员,包括属性、方法、构造函数、字段等。
using System.Reflection;
Type type = job.GetType();
foreach ( MemberInfo memInfo in type.GetMembers() )
if (memInfo is PropertyInfo)
{
// Do Something
}
For Each i in propertyInfo //做一些事情 Next
- dherrin79