DynamicObject.TryInvoke(InvokeBinder, 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 objeto. As classes derivadas da DynamicObject classe podem sobrepor este método para especificar comportamento dinâmico para operações como invocar um objeto ou um delegado.
public:
virtual bool TryInvoke(System::Dynamic::InvokeBinder ^ binder, cli::array <System::Object ^> ^ args, [Runtime::InteropServices::Out] System::Object ^ % result);
public virtual bool TryInvoke(System.Dynamic.InvokeBinder binder, object[] args, out object result);
abstract member TryInvoke : System.Dynamic.InvokeBinder * obj[] * obj -> bool
override this.TryInvoke : System.Dynamic.InvokeBinder * obj[] * obj -> bool
Public Overridable Function TryInvoke (binder As InvokeBinder, args As Object(), ByRef result As Object) As Boolean
Parâmetros
- binder
- InvokeBinder
Fornece informações sobre a operação de invocação.
- args
- Object[]
Os argumentos que são passados ao objeto durante a operação de invocação. Por exemplo, para a sampleObject(100) operação, onde sampleObject é derivado da DynamicObject classe, args[0] é igual a 100.
- result
- Object
O resultado da invocação do objeto.
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 precisa de uma estrutura de dados para armazenar representações textuais e numéricas dos números. Quer poder especificar o valor de cada propriedade individualmente e também poder inicializar todas as propriedades numa única instrução.
O exemplo de código seguinte demonstra a DynamicNumber classe, que é derivada da DynamicObject classe.
DynamicNumber sobrepõe o TryInvoke método para permitir a inicialização de todas as propriedades de uma só vez. Também sobrepõe os TrySetMember métodos e TryGetMember para permitir o acesso às propriedades individuais dos objetos.
// The class derived from DynamicObject.
public class DynamicNumber : DynamicObject
{
// The inner dictionary to store field names and values.
Dictionary<string, object> dictionary
= new Dictionary<string, object>();
// Get the property value.
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
return dictionary.TryGetValue(binder.Name, out result);
}
// Set the property value.
public override bool TrySetMember(
SetMemberBinder binder, object value)
{
dictionary[binder.Name] = value;
return true;
}
// Initializing properties with arguments' values.
public override bool TryInvoke(
InvokeBinder binder, object[] args, out object result)
{
// The invoke operation in this case takes two arguments.
// The first one is integer and the second one is string.
if ((args.Length == 2) &&
(args[0].GetType() == typeof(int)) &&
(args[1].GetType() == typeof(String)))
{
// If the property already exists,
// its value is changed.
// Otherwise, a new property is created.
if (dictionary.ContainsKey("Numeric"))
dictionary["Numeric"] = args[0];
else
dictionary.Add("Numeric", args[0]);
if (dictionary.ContainsKey("Textual"))
dictionary["Textual"] = args[1];
else
dictionary.Add("Textual", args[1]);
result = true;
return true;
}
else
{
// If the number of arguments is wrong,
// or if arguments are of the wrong type,
// the method returns false.
result = false;
return false;
}
}
}
class Program
{
static void Test(string[] args)
{
// Creating a dynamic object.
dynamic number = new DynamicNumber();
// Adding and initializing properties.
// The TrySetMember method is called.
number.Numeric = 1;
number.Textual = "One";
// Printing out the result.
// The TryGetMember method is called.
Console.WriteLine(number.Numeric + " " + number.Textual);
// Invoking an object.
// The TryInvoke method is called.
number(2, "Two");
Console.WriteLine(number.Numeric + " " + number.Textual);
// The following statement produces a run-time exception
// because in this example the method invocation
// expects two arguments.
// number(0);
}
}
// This code example produces the following output:
// 1 One
// 2 Two
Observações
As classes derivadas da DynamicObject classe podem sobrepor este método para especificar como as operações que invocam um objeto devem ser realizadas 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.)
Se este método for sobreposto, é automaticamente invocado quando se tem uma operação como sampleObject(100), onde sampleObject é derivado da DynamicObject classe.
A operação para invocar um objeto é suportada em C#, mas não no Visual Basic. O compilador Visual Basic nunca emite código para usar este método, e a linguagem Visual Basic não suporta sintaxe como sampleObject(100).