Compartir a través de


DynamicObject.TryInvokeMember Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Provides the implementation for operations that invoke a member. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as calling a method.

Namespace:  System.Dynamic
Assembly:  System.Core (in System.Core.dll)

Syntax

'Declaration
Public Overridable Function TryInvokeMember ( _
    binder As InvokeMemberBinder, _
    args As Object(), _
    <OutAttribute> ByRef result As Object _
) As Boolean
public virtual bool TryInvokeMember(
    InvokeMemberBinder binder,
    Object[] args,
    out Object result
)

Parameters

  • binder
    Type: System.Dynamic.InvokeMemberBinder
    Provides information about the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the statement sampleObject.SampleMethod(100), where sampleObject is an instance of the class derived from the DynamicObject class, binder.Name returns "SampleMethod". The binder.IgnoreCase property specifies whether the member name is case-sensitive.
  • args
    Type: array<System.Object[]
    The arguments that are passed to the object member during the invoke operation. For example, for the statement sampleObject.SampleMethod(100), where sampleObject is derived from the DynamicObject class, args[0] is equal to 100.
  • result
    Type: System.Object%
    The result of the member invocation.

Return Value

Type: System.Boolean
true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)

Remarks

Classes derived from the DynamicObject class can override this method to specify how operations that invoke an object member should be performed for a dynamic object. When the method is not overridden, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)

If this method is overridden, it is automatically invoked when you perform an operation like sampleObject.SampleMethod(100), where sampleObject is derived from the DynamicObject class.

You can also add your own methods to classes that are derived from the DynamicObject class. For example, if you override the TryInvokeMember method, the dynamic dispatch system first attempts to determine whether the specified method exists in the class. If it does not find the method, it uses the TryInvokeMember implementation.

Examples

Assume that you want to provide alternative syntax for accessing values in a dictionary, so that instead of writing sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" in Visual Basic), you can write sampleDictionary.Text = "Sample text". Also, you want to be able to call all the standard dictionary methods on this dictionary.

The following code example demonstrates the DynamicDictionary class, which is derived from the DynamicObject class. The DynamicDictionary class contains an object of the Dictionary<string, object> type (Dictionary(Of String, Object) in Visual Basic) to store the key-value pairs. It overrides the TryInvokeMember method to support methods of the Dictionary<TKey, TValue> class and overrides the TrySetMember and TryGetMember methods to support the new syntax. It also provides a Print method, which prints out all dictionary keys and values.

' 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(outputBlock As System.Windows.Controls.TextBlock)
        For Each pair In dictionary
            outputBlock.Text &= pair.Key & " " & pair.Value & vbCrLf
        Next
        If (dictionary.Count = 0) Then
            outputBlock.Text &= "No elements in the dictionary." & vbCrLf
        End If
    End Sub
End Class

Sub Demo(outputBlock As System.Windows.Controls.TextBlock)
    ' 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(outputBlock)

    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(outputBlock)

    ' 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.
// Add using System.Reflection;
// to the beginning of the file.

// The class derived from DynamicObject.
public class DynamicDictionary : DynamicObject
{
   System.Windows.Controls.TextBlock outputBlock;

   public DynamicDictionary(System.Windows.Controls.TextBlock outputBlock)
   {
      this.outputBlock = outputBlock;
   }

   // 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)
         outputBlock.Text += pair.Key + " " + pair.Value + "\n";
      if (dictionary.Count == 0)
         outputBlock.Text += "No elements in the dictionary.\n";
   }
}

class Program
{
   static void Demo(System.Windows.Controls.TextBlock outputBlock, 
                    string[] args)
   {
      // Creating a dynamic dictionary.
      dynamic person = new DynamicDictionary(outputBlock);

      // 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();

      outputBlock.Text +=
          "Removing all the elements from the dictionary." + "\n";

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

Version Information

Silverlight

Supported in: 5, 4

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.