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
0 Int32 CompareTo(System.Object)
1 Int32 CompareTo(Int32)
2 Boolean Equals(System.Object)
// etc. Total 19 items.
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 way to get all members?
Aucun commentaire:
Enregistrer un commentaire