Ler em inglês

Compartilhar via


Type.FindInterfaces(TypeFilter, Object) Método

Definição

Retorna uma matriz de objetos Type que representa uma lista filtrada das interfaces implementadas ou herdadas pelo Type atual.

C#
public virtual Type[] FindInterfaces(System.Reflection.TypeFilter filter, object? filterCriteria);
C#
public virtual Type[] FindInterfaces(System.Reflection.TypeFilter filter, object filterCriteria);

Parâmetros

filter
TypeFilter

O delegado que compara as interfaces com filterCriteria.

filterCriteria
Object

Os critérios de pesquisa que determinam se uma interface deve ser incluída na matriz retornada.

Retornos

Type[]

Uma matriz de objetos Type que representa uma lista filtrada das interfaces implementadas ou herdadas pelo Type atual ou uma matriz vazia se nenhuma interface correspondente ao filtro for implementada ou herdada pelo Type atual.

Implementações

Exceções

filter é null.

Um inicializador estático é invocado e lança uma exceção.

Exemplos

O exemplo a seguir localiza a interface especificada implementada ou herdada pelo tipo especificado e exibe os nomes da interface.

C#
using System;
using System.Xml;
using System.Reflection;

public class MyFindInterfacesSample
{
    public static void Main()
    {
        try
        {
            XmlDocument myXMLDoc = new XmlDocument();
            myXMLDoc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" + "</book>");
            Type myType = myXMLDoc.GetType();

            // Specify the TypeFilter delegate that compares the
            // interfaces against filter criteria.
            TypeFilter myFilter = new TypeFilter(MyInterfaceFilter);
            String[] myInterfaceList = new String[2]
                {"System.Collections.IEnumerable",
                "System.Collections.ICollection"};
            for(int index=0; index < myInterfaceList.Length; index++)
            {
                Type[] myInterfaces = myType.FindInterfaces(myFilter,
                    myInterfaceList[index]);
                if (myInterfaces.Length > 0)
                {
                    Console.WriteLine("\n{0} implements the interface {1}.",
                        myType, myInterfaceList[index]);	
                    for(int j =0;j < myInterfaces.Length;j++)
                        Console.WriteLine("Interfaces supported: {0}.",
                            myInterfaces[j].ToString());
                }
                else
                    Console.WriteLine(
                        "\n{0} does not implement the interface {1}.",
                        myType,myInterfaceList[index]);	
            }
        }
        catch(ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: " + e.Message);
        }
        catch(TargetInvocationException e)
        {
            Console.WriteLine("TargetInvocationException: " + e.Message);
        }
        catch(Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }

    public static bool MyInterfaceFilter(Type typeObj,Object criteriaObj)
    {
        if(typeObj.ToString() == criteriaObj.ToString())
            return true;
        else
            return false;
    }
}

Comentários

Este método pode ser substituído por uma classe derivada.

Os Module.FilterTypeName delegados e Module.FilterTypeNameIgnoreCase fornecidos pela System.Reflection.Module classe também podem ser usados, em vez do System.Reflection.TypeFilter delegado.

Todas as interfaces implementadas por essa classe são consideradas durante a pesquisa, seja declaradas por uma classe base ou por essa própria classe.

Esse método pesquisa a hierarquia de classe base, retornando cada uma das interfaces correspondentes que cada classe implementa, bem como todas as interfaces correspondentes que cada uma dessas interfaces implementa (ou seja, o fechamento transitivo das interfaces correspondentes é retornado). Nenhuma interface duplicada é retornada.

Se o atual Type representar um parâmetro de tipo na definição de um tipo genérico ou método genérico, FindInterfaces pesquisará todas as interfaces declaradas nas restrições no parâmetro de tipo e todas as interfaces herdadas por meio das interfaces declaradas nas restrições. Se o atual Type representar um argumento de tipo de um tipo genérico, FindInterfaces pesquisa todas as interfaces implementadas pelo tipo, se correspondem ou não às restrições.

Observação

FindInterfaces pode retornar interfaces genéricas, mesmo em tipos que não são genéricos. Por exemplo, um tipo não geral pode implementar IEnumerable<int> (IEnumerable(Of Integer) no Visual Basic).

Aplica-se a

Produto Versões
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Confira também