C# 中的 Type.GetMembers() 方法

2024 年 8 月 29 日 | 4 分钟阅读

Type.GetMembers() 函数是一项强大的反射技术,它允许开发人员在运行时访问有关类型组件(字段、属性、方法、事件等)的信息。反射是 C# 中一种允许我们在程序执行期间观察和与类型、程序集和对象元数据进行交互的功能。

GetMembers() 函数属于 System.Type 类,代表 .NET Framework 公共类型系统 (CTS) 中的一个类型。它返回一个 MemberInfo 对象集合,每个对象代表该类型的一个成员。

语法

它具有以下语法:

此函数会生成一个 MemberInfo 对象数组,其中包含属于当前类型的全部公共成员。如果当前 Type 有公共成员,它将返回一个空的 MemberInfo 类型数组。

示例

让我们通过一个示例来说明 C# 中的 Type.GetMember() 方法。

文件名:GetMembers.cs

输出

The Fields of the current type is as follows: 
Boolean Equals(System.Object)
 Int32 GetHashCode()
 System.Type GetType()
 System.String ToString()
 Void .ctor()

示例 2

让我们通过一个示例来说明 C# 中的 Type.GetMember() 方法。

文件名:GetMembers2.cs

输出

The Fields of the current type is as follows: 
Int32 CompareTo(System.Object)
Int32 CompareTo(Int32)
 Boolean Equals(System.Object)
 Boolean Equals(Int32)
 Int32 GetHashCode()
 System.String ToString()

GetMembers(BindingFlags) 方法

此方法根据派生类中重写时提供的绑定约束来搜索当前 Type 声明的成员。

语法

它具有以下语法:

此函数接受一个 BindingFlags 位掩码来确定搜索方法,或者在未指定任何内容时返回空数组。

返回值

此函数提供一个 MemberInfo 对象数组,指示当前 Type 声明的、与绑定限制匹配的所有成员。如果当前 Type 未声明任何成员,或者当前定义的成员都不符合绑定条件,则会返回一个空的 MemberInfo 类型数组。

以下程序解释了上述方法的应用。

示例 1

输出

The Fields of the current type is as follows: 
Boolean Equals(System.Object)
 Int32 GetHashCode()
 System.Type GetType()
 System.String ToString()
 Void .ctor()

示例 2

让我们通过另一个示例来说明 C# 中的 Type.GetMember() 方法。

输出

The Field of the current type is as follows: 
Int32 Parse(System.String)
Int32 Parse(System.String, System.Globalization.NumberStyles)
 Int32 Parse(System.String, System.IFormatProvider)
 Int32 Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider)
 Int32 Parse(System.ReadOnlySpan`1[System.Char], System.Globalization.NumberStyles, System.IFormatProvider)
Boolean TryParse(System.String, Int32 ByRef)
 Boolean TryParse(System.ReadOnlySpan`1[System.Char], Int32 ByRef)
 Boolean TryParse(System.String, System.Globalization.NumberStyles, System.IFormatProvider, Int32 ByRef)
 Boolean TryParse(System.ReadOnlySpan`1[System.Char], System.Globalization.NumberStyles, System.IFormatProvider, Int32 ByRef)
 System.Int32 MaxValue
System.Int32 MinValue