DynamicObject.TryInvoke(InvokeBinder, Object[], Object) Méthode

Définition

Fournit l'implémentation pour les opérations qui appellent un objet. 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'un objet ou d'un délégué.

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

Paramètres

binder
InvokeBinder

Fournit des informations sur l'opération d'appel.

args
Object[]

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

result
Object

Résultat de l'appel de l'objet.

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 avez besoin d’une structure de données pour stocker des représentations textuelles et numériques de nombres. Vous souhaitez pouvoir spécifier la valeur de chaque propriété individuellement et pouvoir initialiser toutes les propriétés dans une instruction unique.

L’exemple de code suivant illustre la DynamicNumber classe, qui est dérivée de la DynamicObject classe . DynamicNumber remplace la TryInvoke méthode pour activer l’initialisation de toutes les propriétés à la fois. Il remplace également les méthodes et TryGetMember pour permettre l’accès TrySetMember à des propriétés d’objet individuelles.

// The class derived from DynamicObject.
public class DynamicNumber : DynamicObject
{
    // The inner dictionary to store field names and values.
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();

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

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

    // Initializing properties with arguments' values.
    public override bool TryInvoke(
        InvokeBinder binder, object[] args, out object result)
    {
        // The invoke operation in this case takes two arguments.
        // The first one is integer and the second one is string.
        if ((args.Length == 2) &&
            (args[0].GetType() == typeof(int)) &&
            (args[1].GetType() == typeof(String)))
        {
            // If the property already exists,
            // its value is changed.
            // Otherwise, a new property is created.
            if (dictionary.ContainsKey("Numeric"))
                dictionary["Numeric"] = args[0];
            else
                dictionary.Add("Numeric", args[0]);

            if (dictionary.ContainsKey("Textual"))
                dictionary["Textual"] = args[1];
            else
                dictionary.Add("Textual", args[1]);

            result = true;
            return true;
        }

        else
        {
            // If the number of arguments is wrong,
            // or if arguments are of the wrong type,
            // the method returns false.
            result = false;
            return false;
        }
    }
}
class Program
{
    static void Test(string[] args)
    {
        // Creating a dynamic object.
        dynamic number = new DynamicNumber();

        // Adding and initializing properties.
        // The TrySetMember method is called.
        number.Numeric = 1;
        number.Textual = "One";

        // Printing out the result.
        // The TryGetMember method is called.
        Console.WriteLine(number.Numeric + " " + number.Textual);

        // Invoking an object.
        // The TryInvoke method is called.
        number(2, "Two");
        Console.WriteLine(number.Numeric + " " + number.Textual);

        // The following statement produces a run-time exception
        // because in this example the method invocation
        // expects two arguments.
        // number(0);
    }
}

// This code example produces the following output:

// 1 One
// 2 Two

Remarques

Les classes dérivées de la DynamicObject classe peuvent remplacer cette méthode pour spécifier la façon dont les opérations qui appellent un 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 est levée.)

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

L’opération d’appel d’un objet est prise en charge en C#, mais pas en Visual Basic. Le compilateur Visual Basic n’émet jamais de code pour utiliser cette méthode, et le langage Visual Basic ne prend pas en charge la syntaxe telle que sampleObject(100).

S’applique à