So what I have right now is something like this:
PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public);
where obj
is some object.
The problem is some of the properties I want aren't in obj.GetType()
they're in one of the base classes further up. If I stop the debugger and look at obj, the I have to dig through a few "base" entries to see the properties I want to get at. Is there some binding flag I can set to have it return those or do I have to recursively dig through the Type.BaseType
hierarchy and do GetProperties
on all of them?
The Object class is the base class for all the classes in the . Net Framework. It is present in the System namespace.
Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.
GetProperties() Returns all the public properties of the current Type.
Use this:
PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
EDIT: Of course the correct answer is that of Jay. GetProperties()
without parameters is equivalent to GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static )
. The BindingFlags.FlattenHierarchy
plays no role here.
I don't think it's that complicated.
If you remove the BindingFlags
parameter to GetProperties, I think you get the results you're looking for:
class B { public int MyProperty { get; set; } } class C : B { public string MyProperty2 { get; set; } } static void Main(string[] args) { PropertyInfo[] info = new C().GetType().GetProperties(); foreach (var pi in info) { Console.WriteLine(pi.Name); } }
produces
MyProperty2 MyProperty
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With