DynamicObject.TryGetMember(GetMemberBinder, Object) Método

Definição

Fornece a implementação para operações que obtêm valores de membro. As classes derivadas da classe DynamicObject podem substituir este método para especificar o comportamento dinâmico para operações como obtenção de um valor para uma propriedade.

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

Fornece informações sobre o objeto que chamou a operação dinâmica. A propriedade binder.Name fornece o nome do membro no qual a operação dinâmica é executada. Por exemplo, para a instrução Console.WriteLine(sampleObject.SampleProperty), em que sampleObject é uma instância da classe que derivada da classe DynamicObject, binder.Name retorna “SampleProperty”. A propriedade binder.IgnoreCase especifica se o nome do membro diferencia maiúsculas de minúsculas.

result
Object

O resultado da operação get. Por exemplo, se o método é chamado para uma propriedade, atribua result para o valor da propriedade.

Retornos

true se a operação for bem-sucedida; caso contrário, false. Se esse método retornar false, o associador de tempo de execução da linguagem determinará o comportamento. (Na maioria dos casos, uma exceção de tempo de execução é gerada.)

Exemplos

Suponha que você queira fornecer sintaxe alternativa para acessar valores em um dicionário, para que, em vez de escrever sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" no Visual Basic), você possa escrever sampleDictionary.Text = "Sample text". Além disso, essa sintaxe deve não diferenciar maiúsculas de minúsculas, de modo que sampleDictionary.Text seja equivalente a sampleDictionary.text.

O exemplo de código a seguir demonstra a DynamicDictionary classe , que é derivada da DynamicObject classe . A DynamicDictionary classe contém um objeto do Dictionary<string, object> tipo (Dictionary(Of String, Object) no Visual Basic) para armazenar os pares chave-valor e substitui os TrySetMember métodos e TryGetMember para dar suporte à nova sintaxe. Ele também fornece uma Count propriedade , que mostra quantas propriedades dinâmicas o dicionário contém.

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

Comentários

Classes derivadas da DynamicObject classe podem substituir esse método para especificar como as operações que obtêm valores de membro devem ser executadas para um objeto dinâmico. Quando o método não é substituído, o associador de tempo de execução do idioma determina o comportamento. (Na maioria dos casos, uma exceção de tempo de execução é gerada.)

Esse método é chamado quando você tem instruções como Console.WriteLine(sampleObject.SampleProperty), em que sampleObject é uma instância da classe derivada da DynamicObject classe .

Você também pode adicionar seus próprios membros a classes derivadas da DynamicObject classe . Se sua classe definir propriedades e também substituir o TrySetMember método , o DLR (dynamic Language Runtime) primeiro usará o associador de idioma para procurar uma definição estática de uma propriedade na classe . Se não houver essa propriedade, a DLR chamará o TrySetMember método .

Aplica-se a