DynamicObject.TryInvokeMember(InvokeMemberBinder, Object[], Object) Метод

Определение

Предоставляет реализацию для операций, вызывающих член. Классы, производные от класса DynamicObject, могут переопределять этот метод, чтобы задать динамическое поведение для таких операций, как вызов метода.

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

Параметры

binder
InvokeMemberBinder

Предоставляет сведения о динамической операции. Свойство binder.Name предоставляет имя элемента, с которым выполняется динамическая операция. Например, для инструкции sampleObject.SampleMethod(100), где sampleObject является экземпляром класса, производного от DynamicObject класса , binder.Name возвращает "SampleMethod". Свойство binder.IgnoreCase указывает, учитывается ли имя элемента с учетом регистра.

args
Object[]

Аргументы, переданные члену объекта во время операции вызова. Например, для оператора sampleObject.SampleMethod(100), где sampleObject является производным DynamicObject от класса , args[0] равно 100.

result
Object

Результат вызова члена.

Возвращаемое значение

Значение true, если операция выполнена успешно; в противном случае — значение false. Если данный метод возвращает значение false, поведение определяется связывателем среды языка. (В большинстве случаев создается языковое исключение во время выполнения).

Примеры

Предположим, что вы хотите предоставить альтернативный синтаксис для доступа к значениям в словаре, чтобы вместо записи sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" в Visual Basic) можно было написать sampleDictionary.Text = "Sample text". Кроме того, вы хотите иметь возможность вызывать все стандартные методы словаря в этом словаре.

В следующем примере кода демонстрируется DynamicDictionary класс , производный DynamicObject от класса . Класс DynamicDictionary содержит объект Dictionary<string, object> типа (Dictionary(Of String, Object) в Visual Basic) для хранения пар "ключ-значение". Он переопределяет TryInvokeMember метод для поддержки Dictionary<TKey,TValue> методов класса и переопределяет TrySetMember методы и TryGetMember для поддержки нового синтаксиса. Он также предоставляет Print метод , который выводит все ключи и значения словаря.

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

Комментарии

Классы, производные DynamicObject от класса , могут переопределить этот метод, чтобы указать, как операции, вызывающие элемент объекта, должны выполняться для динамического объекта. Если метод не переопределен, связыватель времени выполнения языка определяет поведение. (В большинстве случаев создается языковое исключение во время выполнения).

Если этот метод переопределен, он автоматически вызывается при выполнении такой операции, как sampleObject.SampleMethod(100), где sampleObject является производным DynamicObject от класса .

Вы также можете добавить собственные методы в классы, производные DynamicObject от класса . Например, при переопределении TryInvokeMember метода динамическая система диспетчеризации сначала попытается определить, существует ли указанный метод в классе . Если метод не находит, используется TryInvokeMember реализация .

Этот метод не поддерживает ref параметры и out . Все параметры в массиве args передаются по значению.

Применяется к