DynamicObject.TryInvoke(InvokeBinder, Object[], Object) Metodo

Definizione

Fornisce l'implementazione per operazioni che richiamano un oggetto. Le classi derivate dalla classe DynamicObject possono eseguire l'override di questo metodo per specificare il comportamento dinamico per operazioni quale il richiamo di un oggetto o un delegato.

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

Parametri

binder
InvokeBinder

Fornisce informazioni sull'operazione invoke.

args
Object[]

Argomenti passati all'oggetto durante l'operazione invoke. Ad esempio, per l'operazione sampleObject(100) , dove sampleObject è derivato dalla DynamicObject classe , args[0] è uguale a 100.

result
Object

Risultato della chiamata all'oggetto.

Restituisce

true se l'operazione riesce; in caso contrario, false. Se questo metodo restituisce false, il comportamento viene determinato dal gestore di associazione di runtime del linguaggio. Nella maggior parte dei casi viene generata un'eccezione di runtime specifica del linguaggio.

Esempio

Si supponga di avere bisogno di una struttura di dati per archiviare rappresentazioni testuali e numeriche di numeri. Si vuole essere in grado di specificare il valore per ogni proprietà singolarmente e anche di inizializzare tutte le proprietà in una singola istruzione.

Nell'esempio di codice seguente viene illustrata la DynamicNumber classe derivata dalla DynamicObject classe . DynamicNumber esegue l'override del TryInvoke metodo per abilitare l'inizializzazione di tutte le proprietà contemporaneamente. Esegue anche l'override dei TrySetMember metodi e TryGetMember per abilitare l'accesso alle singole proprietà dell'oggetto.

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

Commenti

Le classi derivate dalla classe possono eseguire l'override DynamicObject di questo metodo per specificare come devono essere eseguite le operazioni che richiamano un oggetto per un oggetto dinamico. Quando il metodo non viene sottoposto a override, il binder di runtime del linguaggio determina il comportamento. Nella maggior parte dei casi viene generata eccezione di runtime.

Se questo metodo viene sottoposto a override, viene richiamato automaticamente quando si dispone di un'operazione come sampleObject(100), dove sampleObject è derivato dalla DynamicObject classe .

L'operazione per richiamare un oggetto è supportata in C# ma non in Visual Basic. Il compilatore Visual Basic non genera mai codice per l'uso di questo metodo e il linguaggio Visual Basic non supporta la sintassi come sampleObject(100).

Si applica a