Skip to content

Instantly share code, notes, and snippets.

@CorbyO
Last active December 8, 2022 03:21
Show Gist options
  • Save CorbyO/7d105d2cedf1176c174da7353ed4268b to your computer and use it in GitHub Desktop.
Save CorbyO/7d105d2cedf1176c174da7353ed4268b to your computer and use it in GitHub Desktop.
C# GetAllMembers for Type
using System;
using System.Collections.ObjctModel;
using System.Reflection;
public static class TypeExtension
{
public static ReadOnlyCollection<MemberInfo> GetAllMembers(this Type type, int capacity = 50)
{
var temp = new List<MemberInfo>(capacity);
for(var t = type; t != null; t = t.BaseType)
{
temp.AddRange(t.GetMembers((BindingFlags)(-1)));
}
return temp.AsReadOnly();
}
}
@CorbyO
Copy link
Author

CorbyO commented Dec 7, 2022

e.g. )

public class A                                                                                                            
{
    private int _a;
    protected int b;
    public int c;
}

public class B : A
{
    private int _aa;
    protected int bb;
    public int cc;
}
public class C<T> : B
{
    private T _aaa;
    protected T bbb;
    public T ccc;
}
public class D : C<char>
{
    private int _aaaa;
    protected int bbbb;
    public int cccc;
}

B b = new D();
foreach (var i in GetAllMembers(b.GetType()))
  {
      switch (i.MemberType)
      {
          case MemberTypes.Field:
              var field = i as FieldInfo;
              Console.WriteLine($"{field.FieldType} {field.Name};");
              break;
          case MemberTypes.Property:
              var property = i as PropertyInfo;
              Console.WriteLine($"{property.PropertyType} {property.Name};");
              break;
          default:
              Console.WriteLine($"{i.GetType()} {i.Name};");
              break;
      }
  }

output:

System.Reflection.RuntimeConstructorInfo .ctor;
System.Int32 _aaaa;
System.Int32 bbbb;
System.Int32 cccc;
System.Reflection.RuntimeConstructorInfo .ctor;
System.Char _aaa;
System.Char bbb;
System.Char ccc;
System.Reflection.RuntimeConstructorInfo .ctor;
System.Int32 _aa;
System.Int32 bb;
System.Int32 cc;
System.Reflection.RuntimeConstructorInfo .ctor;
System.Int32 _a;
System.Int32 b;
System.Int32 c;
System.Reflection.RuntimeMethodInfo GetType;
System.Reflection.RuntimeMethodInfo MemberwiseClone;
System.Reflection.RuntimeMethodInfo Finalize;
System.Reflection.RuntimeMethodInfo ToString;
System.Reflection.RuntimeMethodInfo Equals;
System.Reflection.RuntimeMethodInfo Equals;
System.Reflection.RuntimeMethodInfo ReferenceEquals;
System.Reflection.RuntimeMethodInfo GetHashCode;
System.Reflection.RuntimeConstructorInfo .ctor;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment