-2

I've been through "Questions that may already have your answer" and didn't find the thing I'm looking for. I want to get all members on a type via reflection. When I try

var type = typeof(int);
var members = type.GetMembers();
for(var i = 0; i < members.Length; i++)
    Console.WriteLine($"{i, 2} {members[i]}");

I get 19 members.

I found that some members need specific BindingFlags. Since I don't know those flags and different members have different flags I pass all flags like this:

var type = typeof(int);
var flags =
    BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Instance |BindingFlags.Static |
    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod |
    BindingFlags.CreateInstance | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty |
    BindingFlags.SetProperty | BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty | BindingFlags.ExactBinding |
    BindingFlags.SuppressChangeType | BindingFlags.OptionalParamBinding | BindingFlags.IgnoreReturn;
var members = type.GetMembers(flags);
for(var i = 0; i < members.Length; i++)
    Console.WriteLine($"{i, 2} {members[i]}");

It gives me 34 members. That's exactly what I need.

But is where a more elegant (shorter) way to get all members?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • 2
    Define what you mean by elegant please – nalnpir May 30 '19 at 12:11
  • 3
    You could "cheat" by doing `var flags = (BindingFlags)(-1);` – Matthew Watson May 30 '19 at 12:30
  • 2
    It sets all bits in the BindingFlags to 1. It's a bit nasty though (pun intended... ;) Microsoft's implementation could in theory change one day to throw an exception if an unexpected flag was set. Really should use Adrian's code in the answer below. – Matthew Watson May 30 '19 at 12:31
  • The vast majority of `BindingFlags` are irrelevant for `Type.GetMembers()` and only do anything if you're specifying additional search criteria (e.g. `IgnoreCase` and `OptionalParamBinding `) or affect the behavior of `InvokeMember()` (such as `SetField` and `PutDispProperty `). The only ones that matter when trying to find all members are `Public` and `NonPublic`, `Instance` and `Static`, and `FlattenHierarchy` if desired. – kalimag May 30 '19 at 12:49

1 Answers1

5

You could use LINQ's Aggregate to OR all the different BindingFlags values:

var flags = Enum.GetValues(typeof(BindingFlags))
                .Cast<BindingFlags>()
                .Aggregate((x,y) => x | y);
adjan
  • 13,371
  • 2
  • 31
  • 48