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 클래스에서 DynamicObjectbinder.Name 파생된 클래스의 instance "SampleMethod"를 반환합니다. 속성은 binder.IgnoreCase 멤버 이름이 대/소문자를 구분하는지 여부를 지정합니다.

args
Object[]

호출 연산을 수행하는 동안 개체 멤버에 전달되는 인수입니다. 예를 들어 문 sampleObject.SampleMethod(100)의 경우 는 sampleObject 클래스 args[0] 에서 DynamicObject 파생되며 는 100과 같습니다.

result
Object

멤버 호출의 결과입니다.

반환

작업에 성공하면 true이고, 그렇지 않으면 false입니다. 이 메서드가 false를 반환하는 경우 언어의 런타임 바인더에 따라 동작이 결정됩니다. 대부분의 경우 언어별 런타임 예외가 throw됩니다.

예제

(Visual Basic의 경우)sampleDictionary("Text") = "Sample text"를 작성하는 대신 를 작성 sampleDictionary["Text"] = "Sample text"sampleDictionary.Text = "Sample text"할 수 있도록 사전의 값에 액세스하기 위한 대체 구문을 제공하려는 경우를 가정합니다. 또한 이 사전의 모든 표준 사전 메서드를 호출할 수 있습니다.

다음 코드 예제에서는 DynamicDictionary 클래스에서 파생 되는 클래스를 보여 줍니다 DynamicObject . 클래스에는 DynamicDictionary 키-값 쌍을 Dictionary<string, object> 저장할 형식(Dictionary(Of String, Object) Visual Basic의 경우)의 개체가 포함되어 있습니다. 클래스의 TryInvokeMember 메서드를 지원하도록 메서드를 재정의 Dictionary<TKey,TValue> 하고 및 TryGetMember 메서드를 TrySetMember 재정의하여 새 구문을 지원합니다. 또한 모든 사전 키와 값을 출력하는 메서드를 제공합니다 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 하여 동적 개체에 대해 개체 멤버를 호출하는 작업을 수행하는 방법을 지정할 수 있습니다. 메서드를 재정의하지 않으면 언어의 런타임 바인더가 동작을 결정합니다. 대부분의 경우 언어별 런타임 예외가 throw됩니다.

이 메서드가 재정의되면 와 같은 sampleObject.SampleMethod(100)작업을 수행할 때 자동으로 호출됩니다. 여기서 sampleObject 는 클래스에서 DynamicObject 파생됩니다.

클래스에서 DynamicObject 파생된 클래스에 고유한 메서드를 추가할 수도 있습니다. 예를 들어 메서드를 재정의 TryInvokeMember 하는 경우 동적 디스패치 시스템은 먼저 지정된 메서드가 클래스에 있는지 여부를 확인하려고 시도합니다. 메서드를 찾을 수 없는 경우 구현을 TryInvokeMember 사용합니다.

이 메서드는 및 매개 변수를 out 지원하지 ref 않습니다. 배열의 args 모든 매개 변수는 값으로 전달됩니다.

적용 대상