Type.FindMembers(MemberTypes, BindingFlags, MemberFilter, Object) Método

Definição

Retorna uma matriz filtrada de objetos MemberInfo do tipo do membro especificado.Returns a filtered array of MemberInfo objects of the specified member type.

public:
 virtual cli::array <System::Reflection::MemberInfo ^> ^ FindMembers(System::Reflection::MemberTypes memberType, System::Reflection::BindingFlags bindingAttr, System::Reflection::MemberFilter ^ filter, System::Object ^ filterCriteria);
public virtual System.Reflection.MemberInfo[] FindMembers (System.Reflection.MemberTypes memberType, System.Reflection.BindingFlags bindingAttr, System.Reflection.MemberFilter filter, object filterCriteria);
abstract member FindMembers : System.Reflection.MemberTypes * System.Reflection.BindingFlags * System.Reflection.MemberFilter * obj -> System.Reflection.MemberInfo[]
override this.FindMembers : System.Reflection.MemberTypes * System.Reflection.BindingFlags * System.Reflection.MemberFilter * obj -> System.Reflection.MemberInfo[]
Public Overridable Function FindMembers (memberType As MemberTypes, bindingAttr As BindingFlags, filter As MemberFilter, filterCriteria As Object) As MemberInfo()

Parâmetros

memberType
MemberTypes

Uma combinação bit a bit dos valores de enumeração que indica o tipo de membro a ser pesquisado.A bitwise combination of the enumeration values that indicates the type of member to search for.

bindingAttr
BindingFlags

Uma combinação bit a bit dos valores de enumeração que especificam como a pesquisa é realizada.A bitwise combination of the enumeration values that specify how the search is conducted.

- ou --or- Default para retornar null.Default to return null.

filter
MemberFilter

O delegado que faz as comparações, retornando true se o membro inspecionado no momento corresponder ao filterCriteria. Caso contrário, false.The delegate that does the comparisons, returning true if the member currently being inspected matches the filterCriteria and false otherwise.

filterCriteria
Object

Os critérios de pesquisa que determinam se um membro é retornado na matriz de objetos MemberInfo.The search criteria that determines whether a member is returned in the array of MemberInfo objects.

Os campos de FieldAttributes, MethodAttributes e MethodImplAttributes podem ser usados em conjunto com o delegado FilterAttribute fornecido por essa classe.The fields of FieldAttributes, MethodAttributes, and MethodImplAttributes can be used in conjunction with the FilterAttribute delegate supplied by this class.

Retornos

Uma matriz filtrada de objetos MemberInfo do tipo de membro especificado.A filtered array of MemberInfo objects of the specified member type.

- ou --or- Uma matriz vazia se o Type atual não tiver membros do tipo memberType que correspondam aos critérios de filtro.An empty array if the current Type does not have members of type memberType that match the filter criteria.

Implementações

Exceções

filter é null.filter is null.

Exemplos

O exemplo a seguir localiza todos os membros em uma classe que correspondem aos critérios de pesquisa especificados e, em seguida, exibe os membros correspondentes.The following example finds all the members in a class that match the specified search criteria, and then displays the matched members.

using namespace System;
using namespace System::Reflection;
ref class MyFindMembersClass
{
public:
   static void Test()
   {
      Object^ objTest = gcnew Object;
      Type^ objType = objTest->GetType();
      array<MemberInfo^>^arrayMemberInfo;
      try
      {
         
         //Find all static or public methods in the Object class that match the specified name.
         arrayMemberInfo = objType->FindMembers( MemberTypes::Method, static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Static | BindingFlags::Instance), gcnew MemberFilter( DelegateToSearchCriteria ), "ReferenceEquals" );
         for ( int index = 0; index < arrayMemberInfo->Length; index++ )
            Console::WriteLine( "Result of FindMembers -\t {0}", String::Concat( arrayMemberInfo[ index ], "\n" ) );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( "Exception : {0}", e );
      }

   }

   static bool DelegateToSearchCriteria( MemberInfo^ objMemberInfo, Object^ objSearch )
   {
      
      // Compare the name of the member function with the filter criteria.
      if ( objMemberInfo->Name->Equals( objSearch->ToString() ) )
            return true;
      else
            return false;
   }

};

int main()
{
   MyFindMembersClass::Test();
}

using System;
using System.Reflection;

class MyFindMembersClass
{
    public static void Main()
    {
        Object objTest = new Object();
        Type objType = objTest.GetType ();
        MemberInfo[] arrayMemberInfo;
        try
        {
            //Find all static or public methods in the Object class that match the specified name.
            arrayMemberInfo = objType.FindMembers(MemberTypes.Method,
                BindingFlags.Public | BindingFlags.Static| BindingFlags.Instance,
                new MemberFilter(DelegateToSearchCriteria),
                "ReferenceEquals");

            for(int index=0;index < arrayMemberInfo.Length ;index++)
                Console.WriteLine ("Result of FindMembers -\t"+ arrayMemberInfo[index].ToString() +"\n");                 
        }
        catch (Exception e)
        {
            Console.WriteLine ("Exception : " + e.ToString() );            
        }           
    }
    public static bool DelegateToSearchCriteria(MemberInfo objMemberInfo, Object objSearch)
    {
        // Compare the name of the member function with the filter criteria.
        if(objMemberInfo.Name.ToString() == objSearch.ToString())
            return true;
        else 
            return false;
    }
}

Imports System.Reflection

Class MyFindMembersClass

    Public Shared Sub Main()
        Dim objTest As New Object()
        Dim objType As Type = objTest.GetType()
        Dim arrayMemberInfo() As MemberInfo
        Try
            'Find all static or public methods in the Object 
            'class that match the specified name.
            arrayMemberInfo = objType.FindMembers(MemberTypes.Method, _
                              BindingFlags.Public Or BindingFlags.Static _
                              Or BindingFlags.Instance, _
                              New MemberFilter(AddressOf DelegateToSearchCriteria), _
                              "ReferenceEquals")

            Dim index As Integer
            For index = 0 To arrayMemberInfo.Length - 1
                Console.WriteLine("Result of FindMembers -" + ControlChars.Tab + _
                               arrayMemberInfo(index).ToString() + ControlChars.Cr)
            Next index
        Catch e As Exception
            Console.WriteLine("Exception : " + e.ToString())
        End Try
    End Sub

    Public Shared Function DelegateToSearchCriteria _
                            (ByVal objMemberInfo As MemberInfo, _
                             ByVal objSearch As Object) As Boolean
        ' Compare the name of the member function with the filter criteria.
        If objMemberInfo.Name.ToString() = objSearch.ToString() Then
            Return True
        Else
            Return False
        End If
    End Function 'DelegateToSearchCriteria 
End Class

Comentários

Este método pode ser substituído por uma classe derivada.This method can be overridden by a derived class.

Entre os membros estão propriedades, campos, métodos, eventos etc.Members include properties, methods, fields, events, and so on.

Para o método FindMembers para recuperar informações de membros com êxito, o argumento bindingAttr deve incluir pelo menos um dos BindingFlags.Instance e BindingFlags.Static, juntamente com pelo menos um dos BindingFlags.NonPublic e BindingFlags.Public.For the FindMembers method to successfully retrieve member information, the bindingAttr argument must include at least one of BindingFlags.Instance and BindingFlags.Static, along with at least one of BindingFlags.NonPublic and BindingFlags.Public.

Os seguintes sinalizadores de filtro BindingFlags podem ser usados para definir quais membros devem ser incluídos na pesquisa:The following BindingFlags filter flags can be used to define which members to include in the search:

  • Especifique BindingFlags.Instance para incluir membros de instância na pesquisa.Specify BindingFlags.Instance to include instance members in the search.

  • Especifique BindingFlags.Static para incluir membros estáticos na pesquisa.Specify BindingFlags.Static to include static members in the search.

  • Especifique BindingFlags.Public para incluir membros públicos na pesquisa.Specify BindingFlags.Public to include public members in the search.

  • Especifique BindingFlags.NonPublic para incluir membros não públicos (ou seja, membros particulares, internos e protegidos) na pesquisa.Specify BindingFlags.NonPublic to include non-public members (that is, private, internal, and protected members) in the search.

Os seguintes sinalizadores de modificador BindingFlags podem ser usados para alterar como a pesquisa funciona:The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.DeclaredOnly Pesquisar somente os membros declarados na Type, não os membros que são simplesmente herdados.BindingFlags.DeclaredOnly to search only the members declared on the Type, not members that were simply inherited.

Consulte System.Reflection.BindingFlags para obter mais informações.See System.Reflection.BindingFlags for more information.

Para obter o inicializador de classe (Construtor estático) usando esse método, você deve | especificar BindingFlags.Static BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic no Visual Basic).To get the class initializer (static constructor) using this method, you must specify BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic in Visual Basic). Também é possível obter o inicializador da classe usando-se a propriedade TypeInitializer.You can also get the class initializer using the TypeInitializer property.

Se a Type atual representar um parâmetro de tipo de um tipo genérico ou de um método genérico, FindMembers processará todos os membros declarados pela restrição de classe e as restrições de interface do parâmetro de tipo.If the current Type represents a type parameter of a generic type or generic method, FindMembers processes any members declared by the class constraint and the interface constraints of the type parameter.

O argumento filter pode ser um delegado personalizado do tipo MemberFilter, ou pode ser um dos seguintes delegados predefinidos:The filter argument can be a custom delegate of type MemberFilter, or it can be one of the following predefined delegates:

Aplica-se a

Veja também