DynamicObject.TryGetMember(GetMemberBinder, Object) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Fornece a implementação para operações que obtêm valores membros. As classes derivadas da DynamicObject classe podem sobrepor este método para especificar o comportamento dinâmico para operações como obter 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);
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ção sobre o objeto que chamou a operação dinâmica. A binder.Name propriedade fornece o nome do elemento sobre o qual a operação dinâmica é realizada. Por exemplo, para a Console.WriteLine(sampleObject.SampleProperty) afirmação, onde sampleObject é uma instância da classe derivada da DynamicObject classe, binder.Name devolve "ImagemExemplo". A binder.IgnoreCase propriedade especifica se o nome do membro é distinto a maiúsculas e minúsculas.
- result
- Object
O resultado da operação. Por exemplo, se o método for chamado para uma propriedade, pode atribuir o valor da propriedade a result.
Devoluções
true se a operação for bem-sucedida; caso contrário, false. Se este método devolver false, o binder de tempo de execução da linguagem determina o comportamento. (Na maioria dos casos, é lançada uma exceção em tempo de execução.)
Exemplos
Suponha que quer fornecer uma sintaxe alternativa para aceder a valores num dicionário, de modo que, em vez de escrever sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" em Visual Basic), possa escrever sampleDictionary.Text = "Sample text". Além disso, esta sintaxe deve ser insensível a maiúsculas e minúsculas, pelo que sampleDictionary.Text é equivalente a sampleDictionary.text.
O exemplo de código seguinte demonstra a DynamicDictionary classe, que é derivada da DynamicObject classe. A classe DynamicDictionary contém um objeto do tipo Dictionary<string, object> (Dictionary(Of String, Object) em Visual Basic) para armazenar os pares-chave-valor, e sobrepõe os métodos TrySetMember e TryGetMember para suportar a nova sintaxe. 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
Observações
As classes derivadas da DynamicObject classe podem sobrepor este método para especificar como devem ser realizadas operações que obtêm valores de membro para um objeto dinâmico. Quando o método não é sobreposto, o binder de tempo de execução da linguagem determina o comportamento. (Na maioria dos casos, é lançada uma exceção em tempo de execução.)
Este método é chamado quando se têm afirmações como Console.WriteLine(sampleObject.SampleProperty), onde sampleObject é uma instância da classe derivada da DynamicObject classe.
Também pode adicionar os seus próprios membros a turmas derivadas da DynamicObject classe. Se a sua classe definir propriedades e também sobrescrever o TrySetMember método, o tempo de execução dinâmico da linguagem (DLR) usa primeiro o binder da linguagem para procurar uma definição estática de uma propriedade na classe. Se não existir tal propriedade, o DLR chama o TrySetMember método.