获取类型的成员

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.");
    }
  }
}

输出( 请参阅有关输出顺序的说明 ):

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.

我们也可以使用 GetMembers() 而不通过任何 BindingFlags。这将返回该特定类型的所有公共成员。

有一点需要注意,GetMembers 不会以任何特定的顺序返回成员,所以永远不要依赖 GetMembers 返回的顺序。

查看演示