- Home /
C# Reflection GetProperties returning unwanted info
So a while ago I requested help with reflection and I made some decent progress. At the time I was only using reflection to retrieve FieldInfo using the following:
MonoBehaviour[] scripts = selected.GetComponents<MonoBehaviour>();
for(int i = 0; i < scripts.Length; i++)
{
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
FieldInfo[] fields = scripts[i].GetType().GetFields(flags);
//Rest of logic here
}
This works as expected, I get info from the public fields of the scripts. However when attempting to retrieve properties with the following line of code:
PropertyInfo[] properties = scripts[i].GetType().GetProperties(flags);
Returns a very long list of properties which as far as I knew didn't even exist as part of a script. Here's the list of names returned:
Now the only return that I was expecting was the very first property on the list. While I could just keep using fields some of the objects in my game require code which is triggered when a variable changes, so properties are obviously much more suited. Any help is greatly appreciated.
Answer by Kiwasi · Jun 18, 2014 at 10:21 PM
Add BindingFlags.DeclaredOnly to flags. This will filter out all the inherited properties.
I'm just getting my head around reflection myself. Needless to say I've spent a lot of time on the reference page lately.
Certainly a much easier way of handling things, thank you! :D
Answer by Bunny83 · Jun 18, 2014 at 09:40 PM
Well, those properties are there because your class is derived from MonoBehaviour which is derived from Behaviour which is derived from Component which is derived from UnityEngine.Object and each one adds some more properties to your class. Those are all there, so i'm not sure what exactly you try to figure out?
If MonoBehaviour or any class up the hierarchy would have public fields, you would have get them with GetFields as well. However they don't have any public fields since in OOP you "usually" don't use public fields at all :D --> encapsulation
Anyways, if you want to "filter out" properties which aren't declared in the inspecting class itself, you might want to check the DeclaringType of your property if it's your class.
That explains a lot. I have very little experience using reflection so I wasn't aware of the inheritance nor the hierarchy tree. Thanks very much, I'll make some changes and come back to mark this as an answer once I've had some sleep.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Flip over an object (smooth transition) 3 Answers
C# Using Reflection to Automate finding classes 1 Answer
Finding a method by custom attribute and passing to a UI button 1 Answer