【发布时间】:2010-09-23 18:53:00
【问题描述】:
如何查看自定义对象中的每个属性?它不是一个集合对象,但是对于非集合对象有这样的东西吗?
For Each entry as String in myObject
' Do stuff here...
Next
我的对象中有字符串、整数和布尔属性。
【问题讨论】:
标签: asp.net vb.net properties
如何查看自定义对象中的每个属性?它不是一个集合对象,但是对于非集合对象有这样的东西吗?
For Each entry as String in myObject
' Do stuff here...
Next
我的对象中有字符串、整数和布尔属性。
【问题讨论】:
标签: asp.net vb.net properties
通过使用反射,您可以做到这一点。在 C# 中看起来是这样的;
PropertyInfo[] propertyInfo = myobject.GetType().GetProperties();
添加了VB.Net翻译:
Dim info() As PropertyInfo = myobject.GetType().GetProperties()
【讨论】:
For Each 循环的上下文中是如何工作的?
For Each i in propertyInfo //Do stuff Next
您可以使用反射...使用反射您可以检查类的每个成员(类型)、属性、方法、构造函数、字段等。
using System.Reflection;
Type type = job.GetType();
foreach ( MemberInfo memInfo in type.GetMembers() )
if (memInfo is PropertyInfo)
{
// Do Something
}
【讨论】:
您可以使用 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
【讨论】: