DynamicObject.TryInvokeMember(InvokeMemberBinder, Object[], Object) Método

Definição

Fornece a implementação para operações que invocam um membro.Provides the implementation for operations that invoke a member. As classes derivadas da classe DynamicObject podem substituir esse método a fim de especificar o comportamento dinâmico para operações como chamar um método.Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as calling a method.

public:
 virtual bool TryInvokeMember(System::Dynamic::InvokeMemberBinder ^ binder, cli::array <System::Object ^> ^ args, [Runtime::InteropServices::Out] System::Object ^ % result);
public virtual bool TryInvokeMember (System.Dynamic.InvokeMemberBinder binder, object[] args, out object result);
public virtual bool TryInvokeMember (System.Dynamic.InvokeMemberBinder binder, object?[]? args, out object? result);
abstract member TryInvokeMember : System.Dynamic.InvokeMemberBinder * obj[] * obj -> bool
override this.TryInvokeMember : System.Dynamic.InvokeMemberBinder * obj[] * obj -> bool
Public Overridable Function TryInvokeMember (binder As InvokeMemberBinder, args As Object(), ByRef result As Object) As Boolean

Parâmetros

binder
InvokeMemberBinder

Fornece informações sobre a operação dinâmica.Provides information about the dynamic operation. A propriedade binder.Name fornece o nome do membro no qual a operação dinâmica é executada.The binder.Name property provides the name of the member on which the dynamic operation is performed. Por exemplo, para a instrução sampleObject.SampleMethod(100), em que sampleObject é uma instância da classe derivada da classe DynamicObject, binder.Name retorna "SampleMethod".For example, for the statement sampleObject.SampleMethod(100), where sampleObject is an instance of the class derived from the DynamicObject class, binder.Name returns "SampleMethod". A propriedade binder.IgnoreCase especifica se o nome do membro diferencia maiúsculas de minúsculas.The binder.IgnoreCase property specifies whether the member name is case-sensitive.

args
Object[]

Os argumentos passados ao membro do objeto durante a operação de invocação.The arguments that are passed to the object member during the invoke operation. Por exemplo, para a instrução sampleObject.SampleMethod(100), em que sampleObject é derivado da classe DynamicObject, args[0] é igual a 100.For example, for the statement sampleObject.SampleMethod(100), where sampleObject is derived from the DynamicObject class, args[0] is equal to 100.

result
Object

O resultado da invocação do membro.The result of the member invocation.

Retornos

Boolean

true se a operação for bem-sucedida; caso contrário, false.true if the operation is successful; otherwise, false. Se esse método retornar false, o associador de tempo de execução da linguagem determinará o comportamento.If this method returns false, the run-time binder of the language determines the behavior. (Na maioria dos casos, uma exceção de tempo de execução específica a um idioma é gerada.)(In most cases, a language-specific run-time exception is thrown.)

Exemplos

Suponha que você deseja fornecer uma sintaxe alternativa para acessar valores em um dicionário, para que, em vez de escrever sampleDictionary["Text"] = "Sample text" ( sampleDictionary("Text") = "Sample text" em Visual Basic), você possa escrever sampleDictionary.Text = "Sample text" .Assume that you want to provide alternative syntax for accessing values in a dictionary, so that instead of writing sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" in Visual Basic), you can write sampleDictionary.Text = "Sample text". Além disso, você deseja ser capaz de chamar todos os métodos de dicionário padrão neste dicionário.Also, you want to be able to call all the standard dictionary methods on this dictionary.

O exemplo de código a seguir demonstra a DynamicDictionary classe, que é derivada da DynamicObject classe.The following code example demonstrates the DynamicDictionary class, which is derived from the DynamicObject class. A DynamicDictionary classe contém um objeto do Dictionary<string, object> tipo ( Dictionary(Of String, Object) em Visual Basic) para armazenar os pares de chave-valor.The DynamicDictionary class contains an object of the Dictionary<string, object> type (Dictionary(Of String, Object) in Visual Basic) to store the key-value pairs. Ele substitui o TryInvokeMember método para dar suporte a métodos da Dictionary<TKey,TValue> classe e substitui TrySetMember os TryGetMember métodos e para dar suporte à nova sintaxe.It overrides the TryInvokeMember method to support methods of the Dictionary<TKey,TValue> class and overrides the TrySetMember and TryGetMember methods to support the new syntax. Ele também fornece um Print método, que imprime todas as chaves de dicionário e valores.It also provides a Print method, which prints out all dictionary keys and values.

// Add using System.Reflection;
// to the beginning of the file.

// The class derived from DynamicObject.
public class DynamicDictionary : DynamicObject
{
    // The inner dictionary.
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();

    // Getting a property.
    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        return dictionary.TryGetValue(binder.Name, out result);
    }

    // Setting a property.
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;
        return true;
    }

    // Calling a method.
    public override bool TryInvokeMember(
        InvokeMemberBinder binder, object[] args, out object result)
    {
        Type dictType = typeof(Dictionary<string, object>);
        try
        {
            result = dictType.InvokeMember(
                         binder.Name,
                         BindingFlags.InvokeMethod,
                         null, dictionary, args);
            return true;
        }
        catch
        {
            result = null;
            return false;
        }
    }

    // This methods prints out dictionary elements.
    public void Print()
    {
        foreach (var pair in dictionary)
            Console.WriteLine(pair.Key + " " + pair.Value);
        if (dictionary.Count == 0)
            Console.WriteLine("No elements in the dictionary.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Creating a dynamic dictionary.
        dynamic person = new DynamicDictionary();

        // Adding new dynamic properties.
        // The TrySetMember method is called.
        person.FirstName = "Ellen";
        person.LastName = "Adams";

        // Calling a method defined in the DynmaicDictionary class.
        // The Print method is called.
        person.Print();

        Console.WriteLine(
            "Removing all the elements from the dictionary.");

        // Calling a method that is not defined in the DynamicDictionary class.
        // The TryInvokeMember method is called.
        person.Clear();

        // Calling the Print method again.
        person.Print();

        // The following statement throws an exception at run time.
        // There is no Sample method
        // in the dictionary or in the DynamicDictionary class.
        // person.Sample();
    }
}

// This example has the following output:

// FirstName Ellen
// LastName Adams
// Removing all the elements from the dictionary.
// No elements in the dictionary.
' Add Imports System.Reflection
' to the beginning of the file.

' The class derived from DynamicObject.
Public Class DynamicDictionary
    Inherits DynamicObject

    ' The inner dictionary.
    Dim dictionary As New Dictionary(Of String, Object)

    ' Getting a property value.
    Public Overrides Function TryGetMember(
        ByVal binder As System.Dynamic.GetMemberBinder,
        ByRef result As Object) As Boolean

        Return dictionary.TryGetValue(binder.Name, result)
    End Function

    ' Setting a property value.
    Public Overrides Function TrySetMember(
        ByVal binder As System.Dynamic.SetMemberBinder,
        ByVal value As Object) As Boolean

        dictionary(binder.Name) = value
        Return True
    End Function


    ' Calling a method.
    Public Overrides Function TryInvokeMember(
        ByVal binder As System.Dynamic.InvokeMemberBinder,
        ByVal args() As Object, ByRef result As Object) As Boolean

        Dim dictType As Type = GetType(Dictionary(Of String, Object))
        Try
            result = dictType.InvokeMember(
                         binder.Name,
                         BindingFlags.InvokeMethod,
                         Nothing, dictionary, args)
            Return True
        Catch ex As Exception
            result = Nothing
            Return False
        End Try
    End Function

    ' This method prints out dictionary elements.
    Public Sub Print()
        For Each pair In dictionary
            Console.WriteLine(pair.Key & " " & pair.Value)
        Next
        If (dictionary.Count = 0) Then
            Console.WriteLine("No elements in the dictionary.")
        End If
    End Sub
End Class

Sub Test()
    ' Creating a dynamic dictionary.
    Dim person As Object = New DynamicDictionary()

    ' Adding new dynamic properties.
    ' The TrySetMember method is called.
    person.FirstName = "Ellen"
    person.LastName = "Adams"

    ' Calling a method defined in the DynmaicDictionary class.
    ' The Print method is called.
    person.Print()

    Console.WriteLine(
        "Removing all the elements from the dictionary.")

    ' Calling a method that is not defined in the DynamicDictionary class.
    ' The TryInvokeMember method is called.
    person.Clear()

    ' Calling the Print method again.
    person.Print()

    ' The following statement throws an exception at run time.
    ' There is no Sample method 
    ' in the dictionary or in the DynamicDictionary class.
    ' person.Sample()
End Sub


' This example has the following output:

' FirstName Ellen 
' LastName Adams
' Removing all the elements from the dictionary.
' No elements in the dictionary.

Comentários

Classes derivadas da DynamicObject classe podem substituir esse método para especificar como as operações que invocam um membro de objeto devem ser executadas para um objeto dinâmico.Classes derived from the DynamicObject class can override this method to specify how operations that invoke an object member should be performed for a dynamic object. Quando o método não é substituído, o associador de tempo de execução do idioma determina o comportamento.When the method is not overridden, the run-time binder of the language determines the behavior. (Na maioria dos casos, uma exceção de tempo de execução específica a um idioma é gerada.)(In most cases, a language-specific run-time exception is thrown.)

Se esse método for substituído, ele será invocado automaticamente quando você executar uma operação como sampleObject.SampleMethod(100) , onde sampleObject é derivado da DynamicObject classe.If this method is overridden, it is automatically invoked when you perform an operation like sampleObject.SampleMethod(100), where sampleObject is derived from the DynamicObject class.

Você também pode adicionar seus próprios métodos a classes derivadas da DynamicObject classe.You can also add your own methods to classes that are derived from the DynamicObject class. Por exemplo, se você substituir o TryInvokeMember método, o sistema de expedição dinâmica tentará primeiro determinar se o método especificado existe na classe.For example, if you override the TryInvokeMember method, the dynamic dispatch system first attempts to determine whether the specified method exists in the class. Se ele não encontrar o método, ele usará a TryInvokeMember implementação.If it does not find the method, it uses the TryInvokeMember implementation.

Este método não oferece suporte ref a out parâmetros e.This method does not support ref and out parameters. Todos os parâmetros na args matriz são passados por valor.All parameters in the args array are passed by value.

Aplica-se a