Reputation: 1112
When trying to get field information using reflection, I need to use the code
SomeObject.GetType().GetField(
"FieldName",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
In particular, I must specify both BindingFlags.NonPublic
and BindingFlags.Instance
. If I only specify one, I get a null return.
If I am only looking at a single field, why do I need to specify multiple binding flag types?
Upvotes: 2
Views: 2293
Reputation: 13679
every BindingFlag
has a meaning
flags do not specify how many fields you'll receive but what kind of field GetField
method should look for
for example if you do not specify NonPublic
then you may not be able to retrieve any private, protected or internal fields
in your case
other common flags
more on BindingFlags
Upvotes: 2
Reputation:
if it is going about: System.Reflection.BindingFlags.Instance
- from msdn:
You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.
That flag is required to determine wheter you want to get Static or Non-Static members (or both).
Next System.Reflection.BindingFlags.NonPublic
tells, that you want to get non-public member (that by default are not visible outside class). Fields are usually private that is why probably you get null
when trying to retreive field without BindingFlags.Public
.
Upvotes: 1
Reputation: 69372
It's how the search is implemented. From MSDN (in the Note
section):
You must specify Instance or Static along with Public or NonPublic or no members will be returned.
Upvotes: 3
Reputation: 112762
The flags form a filter. They define the types of fields returned. If your field is not public and is an instance field (i.e. is not a static field), you need to include these flags.
You could as well specify additional flags like BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static
in order to include other filed types.
Upvotes: 1
Reputation: 32596
These flags play a role of some sort of a filter.
If you omit BindingFlags.NonPublic
, GetField()
function does not look for private
, internal
and protected
fields.
And you have to specify either BindingFlags.Instance
or BindingFlags.Static
to define what you are looking for.
See http://msdn.microsoft.com/en-us/library/6ztex2dc.aspx:
You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.
...
Specify BindingFlags.NonPublic to include non-public fields (that is, private, internal, and protected fields) in the search. Only protected and internal fields on base classes are returned; private fields on base classes are not returned.
Upvotes: 4