Type.FindMembers(MemberTypes,BindingFlags,MemberFilter,Object)方法用于返回指定成员类型的MemberInfo对象的过滤数组。
句法:
public virtual System.Reflection.MemberInfo[] FindMembers (System.Reflection.MemberTypes memberType, System.Reflection.BindingFlags bindingAttr, System.Reflection.MemberFilter filter, object filterCriteria);
参数:
- memberType:表示要搜索的成员类型。
- bindingAttr:用于指定进行搜索的方式或为零,以返回null。
- filter:进行比较,如果当前正在检查的成员与filterCriteria相匹配,则返回true,否则返回false。
- filterCriteria:确定是否在MemberInfo对象数组中返回成员的搜索条件。
以下BindingFlags过滤器标志可用于定义要在搜索中包括的成员:
- 您必须指定BindingFlags.Instance或BindingFlags.Static才能获得回报。
- 指定BindingFlags.Instance以在搜索中包括实例成员。
- 指定BindingFlags.Static以在搜索中包括静态成员。
- 指定BindingFlags.Public以在搜索中包括公共成员。
- 指定BindingFlags.NonPublic以在搜索中包括非公共成员(即私有成员,内部成员和受保护成员)。
返回值:该方法返回指定成员类型的MemberInfo对象的过滤数组。或类型为MemberInfo的空数组,
异常:如果filter为null,则此方法将引发ArgumentNullException 。
例子:
// C# program to demonstrate the
// Type.FindMembers(MemberTypes,
// BindingFlags, MemberFilter,
// Object) Method
using System;
using System.Globalization;
using System.Reflection;
class GFG {
// Main Method
public static void Main()
{
// Declaring and intializing object of Type
Type objType = typeof(string);
// Creating try-catch block for handling Exception
try {
// Declaring and initializing the object of MemberTypes
// that indicates the type of member to search for.
MemberTypes mt = MemberTypes.All;
// Declaring and initializing the object of BindingFlags
// that specify how the search is conducted.
BindingFlags ba = BindingFlags.Public
| BindingFlags.Instance;
// Declaring and intializing MemberFilter
// which help the delegate that compares
// the MemberInfo against filterCriteria.
MemberFilter mf = new MemberFilter(Search);
// Declaring and intializing object of filterCriteria
// the search criteria that determines whether a member is
// returned in the array of MemberInfo objects or not
object filterCriteria = "Equals";
// Getting filterd array of MemberInfo by
// using FindMembers() Method
MemberInfo[] info = objType.FindMembers(mt, ba, mf, filterCriteria);
// Display the Result
for (int index = 0; index < info.Length; index++)
Console.WriteLine("Result of FindMembers - {0}",
info[index].ToString());
}
// catch ArgumentNullException here
catch (ArgumentNullException e)
{
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
// Defining MyInterfaceFilter
// which helps to fix the certain condition
// on which filtration took place
public static bool Search(MemberInfo info, Object obj)
{
// Compare the name of the member
// function with the filter criteria.
if (info.Name.ToString() == obj.ToString())
return true;
else
return false;
}
}
输出:
Result of FindMembers - Boolean Equals(System.Object)
Result of FindMembers - Boolean Equals(System.String)
Result of FindMembers - Boolean Equals(System.String, System.StringComparison)
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.type.findmembers?view=netcore-3.0