獲取型別的成員
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
返回的順序。