DynamicObject.TryGetMember(GetMemberBinder, Object) Método

Definición

Proporciona la implementación de las operaciones que obtienen valores de miembro. Las clases derivadas de la clase DynamicObject pueden invalidar este método para especificar un comportamiento dinámico para operaciones como obtener el valor de una propiedad.

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

Parámetros

binder
GetMemberBinder

Proporciona información sobre el objeto que llamó a la operación dinámica. La binder.Name propiedad proporciona el nombre del miembro en el que se realiza la operación dinámica. Por ejemplo, para la Console.WriteLine(sampleObject.SampleProperty) instrucción , donde sampleObject es una instancia de la clase derivada de la DynamicObject clase , binder.Name devuelve "SampleProperty". La binder.IgnoreCase propiedad especifica si el nombre del miembro distingue mayúsculas de minúsculas.

result
Object

Resultado de la operación Get. Por ejemplo, si se llama al método para una propiedad, se puede asignar el valor de la propiedad a result.

Devoluciones

true si la operación es correcta; de lo contrario, false. Si este método devuelve false, el enlazador del lenguaje en tiempo de ejecución determina el comportamiento. (En la mayoría de los casos, se inicia una excepción en tiempo de ejecución).

Ejemplos

Supongamos que desea proporcionar una sintaxis alternativa para acceder a los valores de un diccionario, de modo que, en lugar de escribir sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" en Visual Basic), puede escribir sampleDictionary.Text = "Sample text". Además, esta sintaxis debe no distinguir entre mayúsculas y minúsculas, por lo que es sampleDictionary.Text equivalente a sampleDictionary.text.

En el ejemplo de código siguiente se muestra la DynamicDictionary clase , que se deriva de la DynamicObject clase . La DynamicDictionary clase contiene un objeto del Dictionary<string, object> tipo (Dictionary(Of String, Object) en Visual Basic) para almacenar los pares clave-valor e invalida los TrySetMember métodos y TryGetMember para admitir la nueva sintaxis. También proporciona una Count propiedad , que muestra cuántas propiedades dinámicas contiene el diccionario.

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

Comentarios

Las clases derivadas de la DynamicObject clase pueden invalidar este método para especificar cómo se deben realizar las operaciones que obtienen valores de miembro para un objeto dinámico. Cuando el método no se invalida, el enlazador en tiempo de ejecución del lenguaje determina el comportamiento. (En la mayoría de los casos, se inicia una excepción en tiempo de ejecución).

Se llama a este método cuando tiene instrucciones como Console.WriteLine(sampleObject.SampleProperty), donde sampleObject es una instancia de la clase derivada de la DynamicObject clase .

También puede agregar sus propios miembros a las clases derivadas de la DynamicObject clase . Si la clase define las propiedades y también invalida el TrySetMember método , el entorno de ejecución de lenguaje dinámico (DLR) usa primero el enlazador de lenguaje para buscar una definición estática de una propiedad en la clase . Si no hay ninguna propiedad de este tipo, DLR llama al TrySetMember método .

Se aplica a