I have an abstract class — let's nam开发者_StackOverflowe it Base
. This class contains some properties. Moreover, I have another class, inherited from class Base
— let's name it Child
. Child
is not abstract.
I want to access the properties from class Base
with Reflection, and only those properties declared in Base
.
The following code is of course not possible, because I can't create an instance of an abstract class
Base base = new Base();
Type type = base.GetType();
PropertyInfo[] propInfos =
type.GetProperties(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly
);
The following code is possible, but I get all properties, those defined in Base
as well as those defined in Child
.
Child child = new Child();
Type type = child.GetType();
PropertyInfo[] propInfos =
type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
How can I get all properties of class Base
via Reflection?
Try this:
Type type = typeof(A);
PropertyInfo[] propInfos
= type.GetProperties(BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.DeclaredOnly);
Invoking GetType()
on an object is only one of the ways of getting a Type
object. Another, which works even for abstract
classes, is typeof()
. Using the BindingFlags.DeclaredOnly
option with typeof(A).GetProperties
should do the trick.
精彩评论