简体   繁体   中英

Get properties from class object using reflection where property should be public and having get or get and set both

How to use BindingFlags with reflection to get the properties those are public and decorated with get value or get and set value both.

I used following code but it does not return any property.

var properties = obj.GetType().GetProperties(BindingFlags.Public & BindingFlags.Instance & BindingFlags.GetProperty);

The other answer is correct, but lacking explanation.

Context

There is a counterintuitive operation here, whereby merging flags using the | operator creates a merged flag that semantically acts as an "and" value.

This is related to how humans use "and" differently than cold logic does. For example:

Tom and Bob are able to fix the car.

It doesn't mean that Tom && Bob (both of them) must be present for the car to be fixed, it means that Tom || Bob Tom || Bob (ie at least one of them) needs to be present for the car to be fixed.

Similarly, while "and" in English often means the logical OR, "or" in English often means the logical XOR.

You can have a burger or a milkshake.

This is generally taken to mean that you're allowed to choose one, not two, making it an exclusive or (XOR).

Always be very careful of "and/or" in English versus logic. Humans are not as logical as you'd hope.


Example

For the sake of example, let's say that

BindingFlags.Public   = 0001
BindingFlags.Instance = 0010

What we want to achieve, is a combined flag where both flags are present, so 0011 .

When you use & , the result will only contain 1-bits when both values have a 1-bit there.

  0001    // BindingFlags.Public
  0010    // BindingFlags.Instance
& ----
  0000    // No flags

Since the result is "no flags" (all 0), you are asking GetProperties() to return you objects that don't have any binding flags set. And since BindingFlags is a comprehensive set of flags, there are no objects with no flags.

When you use | , the result will combine all 1-bits that at least one of the members has.

  0001    // BindingFlags.Public
  0010    // BindingFlags.Instance
| ----
  0011    // BindingFlags.Public "and" BindingFlags.Instance

In this case, you are asking GetProperties() to return you objects that have both the Public and Instance flags set (ie their third and fourth bit must be 1)

So, in short, in order to get a combined "A and B" flag, you must calculate A | B A | B .

You should not be using the bitwise AND ( & ), but the bitwise OR ( | ):

var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM