DynamicObject.TryInvokeMember(InvokeMemberBinder, Object[], Object) Metoda

Definice

Poskytuje implementaci operací, které volají člena. Třídy odvozené z DynamicObject třídy mohou přepsat tuto metodu k určení dynamického chování operací, jako je volání metody.

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

Parametry

binder
InvokeMemberBinder

Poskytuje informace o dynamické operaci. Vlastnost binder.Name poskytuje název člena, na kterém je dynamická operace provedena. Například pro příkaz sampleObject.SampleMethod(100), kde sampleObject je instance třídy odvozené z DynamicObject třídy, binder.Name vrátí "SampleMethod". Vlastnost binder.IgnoreCase určuje, zda je název členu rozlišovat velká a malá písmena.

args
Object[]

Argumenty předané členu objektu během operace vyvolání. Například pro příkaz sampleObject.SampleMethod(100), kde sampleObject je odvozen z DynamicObject třídy, args[0] je rovna 100.

result
Object

Výsledek vyvolání člena.

Návraty

trueje-li operace úspěšná; v opačném případě . false Pokud tato metoda vrátí false, run-time binder jazyka určuje chování. (Ve většině případů se vyvolá výjimka za běhu specifická pro jazyk.)

Příklady

Předpokládejme, že chcete zadat alternativní syntaxi pro přístup k hodnotám ve slovníku, takže místo psaní sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" v Visual Basic) můžete psát sampleDictionary.Text = "Sample text". Také chcete, aby bylo možné volat všechny standardní metody slovníku v tomto slovníku.

Následující příklad kódu ukazuje DynamicDictionary třídu, která je odvozena z DynamicObject třídy. Třída DynamicDictionary obsahuje objekt typu Dictionary<string, object> (Dictionary(Of String, Object) v Visual Basic) pro uložení párů klíč-hodnota. Přepíše metodu TryInvokeMember pro podporu metod Dictionary<TKey,TValue> třídy a přepíše TrySetMember metody a TryGetMember metody pro podporu nové syntaxe. Poskytuje také metodu Print , která vytiskne všechny klíče a hodnoty slovníku.

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

Poznámky

Třídy odvozené z DynamicObject třídy mohou přepsat tuto metodu určit, jak operace, které vyvolat člen objektu mají být provedeny pro dynamický objekt. Pokud metoda není přepsána, pořadač za běhu jazyka určuje chování. (Ve většině případů se vyvolá výjimka za běhu specifická pro jazyk.)

Pokud je tato metoda přepsána, je automaticky vyvolána při provádění operace, jako je sampleObject.SampleMethod(100), kde sampleObject je odvozen z DynamicObject třídy.

Můžete také přidat vlastní metody do tříd, které jsou odvozeny z DynamicObject třídy. Pokud například přepíšete metodu TryInvokeMember , systém dynamického odeslání se nejprve pokusí zjistit, zda zadaná metoda existuje ve třídě. Pokud metoda nenajde, použije implementaci TryInvokeMember .

Tato metoda nepodporuje ref a out parametry. Všechny parametry v args poli jsou předány hodnotou.

Platí pro