DynamicObject.TryGetMember(GetMemberBinder, Object) Méthode

Définition

Fournit l'implémentation pour les opérations qui obtiennent des valeurs de membre. Les classes dérivées de la classe DynamicObject peuvent substituer cette méthode afin de spécifier le comportement dynamique pour certaines opérations telles que l'obtention d'une valeur pour une propriété.

public:
 virtual bool TryGetMember(System::Dynamic::GetMemberBinder ^ binder, [Runtime::InteropServices::Out] System::Object ^ % result);
public virtual bool TryGetMember (System.Dynamic.GetMemberBinder binder, out object result);
public virtual bool TryGetMember (System.Dynamic.GetMemberBinder binder, out object? result);
abstract member TryGetMember : System.Dynamic.GetMemberBinder * obj -> bool
override this.TryGetMember : System.Dynamic.GetMemberBinder * obj -> bool
Public Overridable Function TryGetMember (binder As GetMemberBinder, ByRef result As Object) As Boolean

Paramètres

binder
GetMemberBinder

Fournit des informations sur l'objet qui a appelé l'opération dynamique. La binder.Name propriété fournit le nom du membre sur lequel l’opération dynamique est effectuée. Par exemple, pour l’instructionConsole.WriteLine(sampleObject.SampleProperty), où sampleObject est un instance de la classe dérivée de la DynamicObject classe, binder.Name retourne « SampleProperty ». La binder.IgnoreCase propriété spécifie si le nom du membre respecte la casse.

result
Object

Résultat de l'opération d'extraction. Par exemple, si la méthode est appelée pour une propriété, vous pouvez assigner la valeur de la propriété à result.

Retours

true si l'opération réussit ; sinon false. Si cette méthode retourne false, le binder d'exécution du langage détermine le comportement. (Dans la plupart des cas, une exception runtime est levée.)

Exemples

Supposons que vous souhaitiez fournir une autre syntaxe pour accéder aux valeurs dans un dictionnaire, de sorte qu’au lieu d’écrire sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" en Visual Basic), vous pouvez écrire sampleDictionary.Text = "Sample text". En outre, cette syntaxe doit ne pas respecter la casse, ce qui sampleDictionary.Text équivaut à sampleDictionary.text.

L’exemple de code suivant illustre la DynamicDictionary classe, qui est dérivée de la DynamicObject classe . La DynamicDictionary classe contient un objet du Dictionary<string, object> type (Dictionary(Of String, Object) en Visual Basic) pour stocker les paires clé-valeur et remplace les TrySetMember méthodes et TryGetMember pour prendre en charge la nouvelle syntaxe. Il fournit également une Count propriété, qui indique le nombre de propriétés dynamiques que contient le dictionnaire.

// The class derived from DynamicObject.
public class DynamicDictionary : DynamicObject
{
    // The inner dictionary.
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();

    // This property returns the number of elements
    // in the inner dictionary.
    public int Count
    {
        get
        {
            return dictionary.Count;
        }
    }

    // If you try to get a value of a property
    // not defined in the class, this method is called.
    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        // Converting the property name to lowercase
        // so that property names become case-insensitive.
        string name = binder.Name.ToLower();

        // If the property name is found in a dictionary,
        // set the result parameter to the property value and return true.
        // Otherwise, return false.
        return dictionary.TryGetValue(name, out result);
    }

    // If you try to set a value of a property that is
    // not defined in the class, this method is called.
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        // Converting the property name to lowercase
        // so that property names become case-insensitive.
        dictionary[binder.Name.ToLower()] = value;

        // You can always add a value to a dictionary,
        // so this method always returns true.
        return true;
    }
}

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";

        // Getting values of the dynamic properties.
        // The TryGetMember method is called.
        // Note that property names are case-insensitive.
        Console.WriteLine(person.firstname + " " + person.lastname);

        // Getting the value of the Count property.
        // The TryGetMember is not called,
        // because the property is defined in the class.
        Console.WriteLine(
            "Number of dynamic properties:" + person.Count);

        // The following statement throws an exception at run time.
        // There is no "address" property,
        // so the TryGetMember method returns false and this causes a
        // RuntimeBinderException.
        // Console.WriteLine(person.address);
    }
}

// This example has the following output:
// Ellen Adams
// Number of dynamic properties: 2
' The class derived from DynamicObject.
Public Class DynamicDictionary
    Inherits DynamicObject

    ' The inner dictionary.
    Dim dictionary As New Dictionary(Of String, Object)

    ' This property returns the number of elements
    ' in the inner dictionary.
    ReadOnly Property Count As Integer
        Get
            Return dictionary.Count
        End Get
    End Property


    ' If you try to get a value of a property that is
    ' not defined in the class, this method is called.

    Public Overrides Function TryGetMember(
        ByVal binder As System.Dynamic.GetMemberBinder,
        ByRef result As Object) As Boolean

        ' Converting the property name to lowercase
        ' so that property names become case-insensitive.
        Dim name As String = binder.Name.ToLower()

        ' If the property name is found in a dictionary,
        ' set the result parameter to the property value and return true.
        ' Otherwise, return false.
        Return dictionary.TryGetValue(name, result)
    End Function

    Public Overrides Function TrySetMember(
        ByVal binder As System.Dynamic.SetMemberBinder,
        ByVal value As Object) As Boolean

        ' Converting the property name to lowercase
        ' so that property names become case-insensitive.
        dictionary(binder.Name.ToLower()) = value

        ' You can always add a value to a dictionary,
        ' so this method always returns true.
        Return True
    End Function
End Class

Sub Main()
    ' 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"

    ' Getting values of the dynamic properties.
    ' The TryGetMember method is called.
    ' Note that property names are now case-insensitive,
    ' although they are case-sensitive in C#.
    Console.WriteLine(person.firstname & " " & person.lastname)

    ' Getting the value of the Count property.
    ' The TryGetMember is not called, 
    ' because the property is defined in the class.
    Console.WriteLine("Number of dynamic properties:" & person.Count)

    ' The following statement throws an exception at run time.
    ' There is no "address" property,
    ' so the TryGetMember method returns false and this causes
    ' a MissingMemberException.
    ' Console.WriteLine(person.address)
End Sub
' This examples has the following output:
' Ellen Adams
' Number of dynamic properties: 2

Remarques

Les classes dérivées de la DynamicObject classe peuvent remplacer cette méthode pour spécifier la façon dont les opérations qui obtiennent des valeurs membres doivent être effectuées pour un objet dynamique. Lorsque la méthode n’est pas remplacée, le classeur d’exécution du langage détermine le comportement. (Dans la plupart des cas, une exception runtime est levée.)

Cette méthode est appelée lorsque vous avez des instructions telles que Console.WriteLine(sampleObject.SampleProperty), où sampleObject est une instance de la classe dérivée de la DynamicObject classe .

Vous pouvez également ajouter vos propres membres à des classes dérivées de la DynamicObject classe . Si votre classe définit des propriétés et remplace également la TrySetMember méthode, le runtime de langage dynamique (DLR) utilise d’abord le classeur de langage pour rechercher une définition statique d’une propriété dans la classe. S’il n’existe aucune propriété de ce type, le DLR appelle la TrySetMember méthode .

S’applique à