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

成員引動過程的結果。

傳回

Boolean

如果作業成功,則為 true,否則為 false。 如果這個方法傳回 false,語言的執行階段繫結器會決定行為。 (在大多數情況下,將會擲回特定語言的執行階段例外狀況)。

範例

假設您想要提供替代語法來存取字典中的值,如此一來,您便可以撰寫 ,而不是在 Visual Basic) 中撰寫 sampleDictionary["Text"] = "Sample text" sampleDictionary.Text = "Sample text" (sampleDictionary("Text") = "Sample text" 。 此外,您想要能夠在此字典上呼叫所有標準字典方法。

下列程式碼範例示範 DynamicDictionary 衍生自 類別的 DynamicObject 類別。 類別 DynamicDictionary 包含 Visual Basic) 中類型 (Dictionary(Of String, Object) 的物件 Dictionary<string, object> ,用來儲存機碼/值組。 它會覆寫 TryInvokeMember 方法以支援 類別的方法 Dictionary<TKey,TValue> ,並覆寫 TrySetMemberTryGetMember 方法來支援新的語法。 它也提供 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

這個方法不支援 refout 參數。 陣列中的所有 args 參數都會以值傳遞。

適用於