DynamicObject.TryInvokeMember(InvokeMemberBinder, Object[], Object) Metódus

Definíció

A tagot meghívó műveletek implementációját biztosítja. Az osztályból származó osztályok felülbírálhatják ezt a DynamicObject metódust, hogy dinamikus viselkedést adjanak meg az olyan műveletekhez, mint a metódus meghívása.

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

Paraméterek

binder
InvokeMemberBinder

A dinamikus művelettel kapcsolatos információkat nyújt. A binder.Name tulajdonság annak a tagnak a nevét adja meg, amelyen a dinamikus műveletet végrehajtja. Az utasítás sampleObject.SampleMethod(100)esetében például , ahol sampleObject az osztály egy példánya az osztályból DynamicObject származik, binder.Name a "SampleMethod" értéket adja vissza. A binder.IgnoreCase tulajdonság megadja, hogy a tagnév megkülönbözteti-e a kis- és nagybetűket.

args
Object[]

A meghívási művelet során az objektumtagnak átadott argumentumok. Az osztályból sampleObject.SampleMethod(100)sampleObject származtatott utasítás DynamicObjectargs[0] például 100-nak felel meg.

result
Object

A taghívás eredménye.

Válaszok

trueha a művelet sikeres; egyéb esetben. false Ha ez a metódus visszatér false, a nyelv futásidejű kötése határozza meg a viselkedést. (A legtöbb esetben a rendszer nyelvspecifikus futásidejű kivételt ad ki.)

Példák

Tegyük fel, hogy alternatív szintaxist szeretne adni egy szótár értékeinek eléréséhez, hogy ahelyett, hogy sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" Visual Basic) írna, sampleDictionary.Text = "Sample text" írhat. Emellett meg szeretné tudni hívni a szótár összes szabványos szótármetszetét.

Az alábbi példakód az DynamicDictionary osztályból DynamicObject származtatott osztályt mutatja be. A DynamicDictionary osztály a kulcs-érték párok tárolásához Dictionary<string, object> típusú objektumot tartalmaz (Dictionary(Of String, Object) Visual Basic). Felülbírálja az TryInvokeMember osztály metódusait Dictionary<TKey,TValue> támogató metódust, és felülbírálja az TrySetMember új szintaxist támogató és TryGetMember támogató metódusokat. Emellett egy metódust Print is biztosít, amely az összes szótárkulcsot és értéket kinyomtatja.

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

Megjegyzések

Az osztályból származó osztályok felülbírálhatják ezt a DynamicObject metódust, hogy megadják, hogyan kell végrehajtani az objektumtagokat meghívó műveleteket egy dinamikus objektumon. Ha a metódus nincs felülírva, a nyelv futásidejű kötése határozza meg a viselkedést. (A legtöbb esetben a rendszer nyelvspecifikus futásidejű kivételt ad ki.)

Ha ez a metódus felül van bírálva, a rendszer automatikusan meghívja, amikor olyan műveletet hajt végre, mint a sampleObject.SampleMethod(100), ahol sampleObject az DynamicObject osztály származik.

Saját metódusokat is hozzáadhat az osztályból DynamicObject származtatott osztályokhoz. Ha például felülbírálja a TryInvokeMember metódust, a dinamikus diszpécserrendszer először megkísérli megállapítani, hogy a megadott metódus létezik-e az osztályban. Ha nem találja a metódust, az implementációt TryInvokeMember használja.

Ez a módszer nem támogatja és ref nem támogatja out a paramétereket. A tömb minden paraméterét args érték adja át.

A következőre érvényes: