DynamicObject.TryInvokeMember(InvokeMemberBinder, Object[], 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 invocam um membro. As classes derivadas da DynamicObject classe podem sobrepor este método para especificar comportamento dinâmico para operações como chamar um método.
public:
virtual bool TryInvokeMember(System::Dynamic::InvokeMemberBinder ^ binder, cli::array <System::Object ^> ^ args, [Runtime::InteropServices::Out] System::Object ^ % result);
public virtual bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result);
abstract member TryInvokeMember : System.Dynamic.InvokeMemberBinder * obj[] * obj -> bool
override this.TryInvokeMember : System.Dynamic.InvokeMemberBinder * obj[] * obj -> bool
Public Overridable Function TryInvokeMember (binder As InvokeMemberBinder, args As Object(), ByRef result As Object) As Boolean
Parâmetros
- binder
- InvokeMemberBinder
Fornece informações sobre 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 afirmação sampleObject.SampleMethod(100), onde sampleObject é uma instância da classe derivada da DynamicObject classe, binder.Name retorna "SampleMethod". A binder.IgnoreCase propriedade especifica se o nome do membro é distinto a maiúsculas e minúsculas.
- args
- Object[]
Os argumentos que são passados ao elemento objeto durante a operação de invocação. Por exemplo, para a afirmação sampleObject.SampleMethod(100), onde sampleObject é derivado da DynamicObject classe, args[0] é igual a 100.
- result
- Object
Resultado da invocação do membro.
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 específica de tempo de execução da linguagem.)
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, queres poder chamar todos os métodos padrão do dicionário neste dicionário.
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. Sobrepõe o TryInvokeMember método para suportar os métodos da Dictionary<TKey,TValue> classe e sobrepõe os TrySetMember métodos e TryGetMember para suportar a nova sintaxe. Também fornece um Print método que imprime todas as chaves e valores do dicionário.
// Add using System.Reflection;
// to the beginning of the file.
// The class derived from DynamicObject.
public class DynamicDictionary : DynamicObject
{
// 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)
Console.WriteLine(pair.Key + " " + pair.Value);
if (dictionary.Count == 0)
Console.WriteLine("No elements in the dictionary.");
}
}
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";
// Calling a method defined in the DynmaicDictionary class.
// The Print method is called.
person.Print();
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();
// 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.
' 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()
For Each pair In dictionary
Console.WriteLine(pair.Key & " " & pair.Value)
Next
If (dictionary.Count = 0) Then
Console.WriteLine("No elements in the dictionary.")
End If
End Sub
End Class
Sub Test()
' 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()
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()
' 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.
Observações
As classes derivadas da DynamicObject classe podem sobrepor este método para especificar como devem ser realizadas operações que invocam um elemento de objeto 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 específica de tempo de execução da linguagem.)
Se este método for sobreposto, é automaticamente invocado quando se realiza uma operação como sampleObject.SampleMethod(100), onde sampleObject é derivado da DynamicObject classe.
Também podes adicionar os teus próprios métodos às turmas que derivam da DynamicObject turma. Por exemplo, se sobrescreveres o TryInvokeMember método, o sistema de despacho dinâmico tenta primeiro determinar se o método especificado existe na classe. Se não encontrar o método, usa a TryInvokeMember implementação.
Este método não suporta ref parâmetros.out Todos os parâmetros do args array são passados por valor.