|
-
Jan 22nd, 2007, 10:26 AM
#1
Thread Starter
Member
[RESOLVED] Looping through an Object
I have created a Consumer Object and I would like to loop through and display each property. So in my sample code I would like to have 2 message boxes displayed one with "ekim" another with "12987". But my object array, attributes, is always null. Is there a correct way to loop through an object?
public void Testing()
{
CConsumer Consumer = new CConsumer();
Consumer.FirstName = "ekim";
Consumer.LastName = "12987";
System.Reflection.MemberInfo inf = typeof(CConsumer);
object[] attributes;
attributes = inf.GetCustomAttributes(typeof(CConsumer), false);
foreach (Object attribute in attributes)
{
MessageBox.Show(attribute.ToString());
}
}
Thanks
-
Jan 22nd, 2007, 11:54 AM
#2
Re: Looping through an Object
You would use PropertyInfo.
Code:
Type objType = Consumer.GetType();
PropertyInfo[] pi = objType.GetProperties();
foreach(PropertyInfo p in pi)
{
//Now, use p.
}
-
Jan 22nd, 2007, 08:22 PM
#3
Thread Starter
Member
Re: Looping through an Object
Thanks for the response. To display the value just use GetValue
foreach (PropertyInfo p in pi)
{
MessageBox.Show(p.GetValue(Consumer, null).ToString());
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|