C# Language Obtenir les membres d'un type


Exemple

using System;
using System.Reflection;
using System.Linq;
                
public class Program
{
  public static void Main()
  {
    var members = typeof(object)
                    .GetMembers(BindingFlags.Public |
                                BindingFlags.Static |
                                BindingFlags.Instance);
    
    foreach (var member in members)
    {
      bool inherited = member.DeclaringType.Equals( typeof(object).Name );
      Console.WriteLine($"{member.Name} is a {member.MemberType}, " +
                        $"it has {(inherited ? "":"not")} been inherited.");
    }
  }
}

Sortie ( voir note sur l'ordre de sortie plus bas ):

GetType is a Method, it has not been inherited.
GetHashCode is a Method, it has not been inherited.
ToString is a Method, it has not been inherited.
Equals is a Method, it has not been inherited.
Equals is a Method, it has not been inherited.
ReferenceEquals is a Method, it has not been inherited.
.ctor is a Constructor, it has not been inherited.

Nous pouvons également utiliser GetMembers() sans passer par BindingFlags . Cela retournera tous les membres publics de ce type spécifique.

Une chose à noter que GetMembers ne GetMembers pas les membres dans un ordre particulier, alors ne comptez jamais sur l'ordre que GetMembers vous renvoie.

Voir la démo