Share via


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

Définition

Fournit l'implémentation pour les opérations qui appellent un membre. Les classes dérivées de la classe DynamicObject peuvent substituer cette méthode afin de spécifier le comportement dynamique pour certaines opérations telles que l'appel d'une méthode.

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

Paramètres

binder
InvokeMemberBinder

Fournit des informations sur l'opération dynamique. La binder.Name propriété fournit le nom du membre sur lequel l’opération dynamique est effectuée. Par exemple, pour l’instruction sampleObject.SampleMethod(100), où sampleObject est une instance de la classe dérivée de la DynamicObject classe , binder.Name retourne « SampleMethod ». La binder.IgnoreCase propriété spécifie si le nom du membre respecte la casse.

args
Object[]

Arguments passés au membre d'objet pendant l'opération d'appel. Par exemple, pour l’instruction sampleObject.SampleMethod(100), où sampleObject est dérivé de la DynamicObject classe , args[0] est égal à 100.

result
Object

Résultat de l'appel du membre.

Retours

true si l'opération réussit ; sinon false. Si cette méthode retourne false, le binder d'exécution du langage détermine le comportement. (Dans la plupart des cas, une exception runtime spécifique au langage est levée.)

Exemples

Supposons que vous souhaitiez fournir une autre syntaxe pour accéder aux valeurs dans un dictionnaire, de sorte qu’au lieu d’écrire sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" en Visual Basic), vous pouvez écrire sampleDictionary.Text = "Sample text". En outre, vous souhaitez pouvoir appeler toutes les méthodes de dictionnaire standard sur ce dictionnaire.

L’exemple de code suivant illustre la DynamicDictionary classe , qui est dérivée de la DynamicObject classe . La DynamicDictionary classe contient un objet de Dictionary<string, object> type (Dictionary(Of String, Object) en Visual Basic) pour stocker les paires clé-valeur. Il remplace la TryInvokeMember méthode pour prendre en charge les méthodes de la Dictionary<TKey,TValue> classe et remplace les TrySetMember méthodes et TryGetMember pour prendre en charge la nouvelle syntaxe. Il fournit également une Print méthode qui imprime toutes les clés et valeurs de dictionnaire.

// 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.

Remarques

Les classes dérivées de la DynamicObject classe peuvent remplacer cette méthode pour spécifier comment les opérations qui appellent un membre d’objet doivent être effectuées pour un objet dynamique. Lorsque la méthode n’est pas remplacée, le classeur d’exécution du langage détermine le comportement. (Dans la plupart des cas, une exception runtime spécifique au langage est levée.)

Si cette méthode est remplacée, elle est appelée automatiquement lorsque vous effectuez une opération comme sampleObject.SampleMethod(100), où sampleObject est dérivé de la DynamicObject classe .

Vous pouvez également ajouter vos propres méthodes aux classes dérivées de la DynamicObject classe . Par exemple, si vous remplacez la TryInvokeMember méthode, le système de répartition dynamique tente d’abord de déterminer si la méthode spécifiée existe dans la classe . S’il ne trouve pas la méthode, il utilise l’implémentation TryInvokeMember .

Cette méthode ne prend pas en charge les ref paramètres et out . Tous les paramètres du args tableau sont passés par valeur.

S’applique à