reflection PropertyInfo. How to select properties of the derived class?

S

Steve Richter

when enumerating thru the properties of a type, how do I select only
the properties of the derived class? In the example below, the
AddrBookPrompt class is derived from the Form class. When I enumerate
the properties I get all the properties of the base class + the
properties of my derived class.

thanks,


AddrBookPrompt abPmt = new AddrBookPrompt();
abPmt.FirstName = "Steve";
abPmt.LastName = "Richter";

System.Type type = abPmt.GetType();
PropertyInfo[] piArray = type.GetProperties();
foreach (PropertyInfo pi in piArray)
{
ListViewItem item = new ListViewItem(pi.Name);
item.Tag = pi;
item.SubItems.Add(pi.PropertyType.Name);
item.SubItems.Add(pi.Module.Name );
mLvProperties.Items.Add(item);
}
 
J

Jon Skeet [C# MVP]

when enumerating thru the properties of a type, how do I select only
the properties of the derived class? In the example below, the
AddrBookPrompt class is derived from the Form class. When I enumerate
the properties I get all the properties of the base class + the
properties of my derived class.

Use the overload which takes a BindingFlags, and make sure that you
include DeclaredOnly (as well as whatever other flags you want (eg
Instance, Public).

Jon
 
S

Steve Richter

Use the overload which takes a BindingFlags, and make sure that you
include DeclaredOnly (as well as whatever other flags you want (eg
Instance, Public).

where do I specify DeclaredOnly and BindingFlags?

I think I have the answer. I compare the "DeclaringType.Name" of the
property with the Type.Name of the type I am listing the properties
of:

AddrBookPrompt abPmt = new AddrBookPrompt();

System.Type type = abPmt.GetType();
PropertyInfo[] piArray = type.GetProperties();
foreach (PropertyInfo pi in piArray)
{
if (pi.DeclaringType.Name == type.Name)
{
ListViewItem item = new ListViewItem(pi.Name);
item.Tag = pi;
item.SubItems.Add(pi.PropertyType.Name);
item.SubItems.Add(pi.Module.Name);
item.SubItems.Add(pi.DeclaringType.Name);
mLvProperties.Items.Add(item);
}
}

thanks,

-Steve
 
J

Jon Skeet [C# MVP]

Steve Richter said:
where do I specify DeclaredOnly and BindingFlags?

DeclaredOnly is a member of the BindingFlags enum, which you can pass
to GetProperties.
I think I have the answer. I compare the "DeclaringType.Name" of the
property with the Type.Name of the type I am listing the properties
of:

You could do that, but it would be better to get GetProperties to
filter for you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top