DynamicObject.TryBinaryOperation Método

Definição

Fornece implementação para operações binárias. As classes derivadas da classe DynamicObject podem substituir esse método a fim de especificar o comportamento dinâmico para operações como adição e multiplicação.

public:
 virtual bool TryBinaryOperation(System::Dynamic::BinaryOperationBinder ^ binder, System::Object ^ arg, [Runtime::InteropServices::Out] System::Object ^ % result);
public virtual bool TryBinaryOperation (System.Dynamic.BinaryOperationBinder binder, object arg, out object result);
public virtual bool TryBinaryOperation (System.Dynamic.BinaryOperationBinder binder, object arg, out object? result);
abstract member TryBinaryOperation : System.Dynamic.BinaryOperationBinder * obj * obj -> bool
override this.TryBinaryOperation : System.Dynamic.BinaryOperationBinder * obj * obj -> bool
Public Overridable Function TryBinaryOperation (binder As BinaryOperationBinder, arg As Object, ByRef result As Object) As Boolean

Parâmetros

binder
BinaryOperationBinder

Fornece informações sobre a operação binária. A binder.Operation propriedade retorna um ExpressionType objeto . Por exemplo, para a sum = first + second instrução , em que first e second são derivados da DynamicObject classe , binder.Operation retorna ExpressionType.Add.

arg
Object

O operando direito da operação binária. Por exemplo, para a sum = first + second instrução , em que first e second são derivados da DynamicObject classe , arg é igual a second.

result
Object

O resultado da operação binária.

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 específica a um idioma é gerada.)

Exemplos

Suponha que você precise de uma estrutura de dados para armazenar representações textuais e numéricas de números e que deseja definir operações matemáticas básicas, como adição e subtração para esses dados.

O exemplo de código a seguir demonstra a DynamicNumber classe , que é derivada da DynamicObject classe . DynamicNumber substitui o TryBinaryOperation método para habilitar operações matemáticas. Ele também substitui os TrySetMember métodos e TryGetMember para habilitar o acesso aos elementos.

Neste exemplo, há suporte apenas para operações de adição e subtração. Se você tentar escrever uma instrução como resultNumber = firstNumber*secondNumber, uma exceção em tempo de execução será gerada.

// Add using System.Linq.Expressions;
// to the beginning of the file.

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

    // Perform the binary operation.
    public override bool TryBinaryOperation(
        BinaryOperationBinder binder, object arg, out object result)
    {
        // The Textual property contains the textual representaion
        // of two numbers, in addition to the name
        // of the binary operation.
        string resultTextual =
            dictionary["Textual"].ToString() + " "
            + binder.Operation + " " +
            ((DynamicNumber)arg).dictionary["Textual"].ToString();

        int resultNumeric;

        // Checking what type of operation is being performed.
        switch (binder.Operation)
        {
            // Proccessing mathematical addition (a + b).
            case ExpressionType.Add:
                resultNumeric =
                    (int)dictionary["Numeric"] +
                    (int)((DynamicNumber)arg).dictionary["Numeric"];
                break;

            // Processing mathematical substraction (a - b).
            case ExpressionType.Subtract:
                resultNumeric =
                    (int)dictionary["Numeric"] -
                    (int)((DynamicNumber)arg).dictionary["Numeric"];
                break;

            // In case of any other binary operation,
            // print out the type of operation and return false,
            // which means that the language should determine
            // what to do.
            // (Usually the language just throws an exception.)
            default:
                Console.WriteLine(
                    binder.Operation +
                    ": This binary operation is not implemented");
                result = null;
                return false;
        }

        dynamic finalResult = new DynamicNumber();
        finalResult.Textual = resultTextual;
        finalResult.Numeric = resultNumeric;
        result = finalResult;
        return true;
    }
}

class Program
{
    static void Test(string[] args)
    {
        // Creating the first dynamic number.
        dynamic firstNumber = new DynamicNumber();

        // Creating properties and setting their values
        // for the first dynamic number.
        // The TrySetMember method is called.
        firstNumber.Textual = "One";
        firstNumber.Numeric = 1;

        // Printing out properties. The TryGetMember method is called.
        Console.WriteLine(
            firstNumber.Textual + " " + firstNumber.Numeric);

        // Creating the second dynamic number.
        dynamic secondNumber = new DynamicNumber();
        secondNumber.Textual = "Two";
        secondNumber.Numeric = 2;
        Console.WriteLine(
            secondNumber.Textual + " " + secondNumber.Numeric);

        dynamic resultNumber = new DynamicNumber();

        // Adding two numbers. The TryBinaryOperation is called.
        resultNumber = firstNumber + secondNumber;

        Console.WriteLine(
            resultNumber.Textual + " " + resultNumber.Numeric);

        // Subtracting two numbers. TryBinaryOperation is called.
        resultNumber = firstNumber - secondNumber;

        Console.WriteLine(
            resultNumber.Textual + " " + resultNumber.Numeric);

        // The following statement produces a run-time exception
        // because the multiplication operation is not implemented.
        // resultNumber = firstNumber * secondNumber;
    }
}

// This code example produces the following output:

// One 1
// Two 2
// One Add Two 3
// One Subtract Two -1
' Add Imports System.Linq.Expressions
' to the beginning of the file.
' The class derived from DynamicObject.
Public Class DynamicNumber
    Inherits DynamicObject

    ' The inner dictionary to store field names and values.
    Dim dictionary As New Dictionary(Of String, Object)

    ' Get the 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

    ' Set the 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

    ' Perform the binary operation. 
    Public Overrides Function TryBinaryOperation(
        ByVal binder As System.Dynamic.BinaryOperationBinder,
        ByVal arg As Object, ByRef result As Object) As Boolean

        ' The Textual property contains the textual representaion 
        ' of two numbers, in addition to the name of the binary operation.
        Dim resultTextual As String =
            dictionary("Textual") & " " &
            binder.Operation.ToString() & " " &
        CType(arg, DynamicNumber).dictionary("Textual")

        Dim resultNumeric As Integer

        ' Checking what type of operation is being performed.
        Select Case binder.Operation
            ' Proccessing mathematical addition (a + b).
            Case ExpressionType.Add
                resultNumeric =
                CInt(dictionary("Numeric")) +
                CInt((CType(arg, DynamicNumber)).dictionary("Numeric"))

                ' Processing mathematical substraction (a - b).
            Case ExpressionType.Subtract
                resultNumeric =
                CInt(dictionary("Numeric")) -
                CInt((CType(arg, DynamicNumber)).dictionary("Numeric"))

            Case Else
                ' In case of any other binary operation,
                ' print out the type of operation and return false,
                ' which means that the language should determine 
                ' what to do.
                ' (Usually the language just throws an exception.)
                Console.WriteLine(
                    binder.Operation.ToString() &
                    ": This binary operation is not implemented")
                result = Nothing
                Return False
        End Select

        Dim finalResult As Object = New DynamicNumber()
        finalResult.Textual = resultTextual
        finalResult.Numeric = resultNumeric
        result = finalResult
        Return True
    End Function
End Class

Sub Test()
    ' Creating the first dynamic number.
    Dim firstNumber As Object = New DynamicNumber()

    ' Creating properties and setting their values
    ' for the first dynamic number. 
    ' The TrySetMember method is called.
    firstNumber.Textual = "One"
    firstNumber.Numeric = 1

    ' Printing out properties. The TryGetMember method is called.
    Console.WriteLine(
        firstNumber.Textual & " " & firstNumber.Numeric)

    ' Creating the second dynamic number.
    Dim secondNumber As Object = New DynamicNumber()
    secondNumber.Textual = "Two"
    secondNumber.Numeric = 2
    Console.WriteLine(
        secondNumber.Textual & " " & secondNumber.Numeric)

    Dim resultNumber As Object = New DynamicNumber()

    ' Adding two numbers. TryBinaryOperation is called.
    resultNumber = firstNumber + secondNumber
    Console.WriteLine(
        resultNumber.Textual & " " & resultNumber.Numeric)

    ' Subtracting two numbers. TryBinaryOperation is called.
    resultNumber = firstNumber - secondNumber
    Console.WriteLine(
        resultNumber.Textual & " " & resultNumber.Numeric)

    ' The following statement produces a run-time exception
    ' because the multiplication operation is not implemented.
    ' resultNumber = firstNumber * secondNumber
End Sub

' This code example produces the following output:

' One 1
' Two 2
' One Add Two 3
' One Subtract Two -1

Comentários

Classes derivadas da DynamicObject classe podem substituir esse método para especificar como as operações binárias 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 específica a um idioma é gerada.)

Esse método é chamado quando você tem operações binárias, como adição ou multiplicação. Por exemplo, se o TryBinaryOperation método for substituído, ele será invocado automaticamente para instruções como sum = first + second ou multiply = first*second, em que first é derivado da DynamicObject classe .

Você pode obter informações sobre o tipo da operação binária usando a Operation propriedade do binder parâmetro .

Se o objeto dinâmico for usado apenas em C# e Visual Basic, a binder.Operation propriedade poderá ter um dos seguintes valores da ExpressionType enumeração. No entanto, em outras linguagens, como IronPython ou IronRuby, você pode ter outros valores.

Valor Descrição C# Visual Basic
Add Uma operação de adição sem verificação de estouro para operandos numéricos. a + b a + b
AddAssign Uma operação de atribuição composta de adição sem verificação de estouro, para operandos numéricos. a += b Não há suporte.
And Uma operação bit a bit AND . a & b a And b
AndAssign Uma operação de atribuição composta bit a bit AND . a &= b Não há suporte.
Divide Uma operação de divisão aritmética. a / b a / b
DivideAssign Uma operação de atribuição composta de divisão aritmética. a /= b Não há suporte.
ExclusiveOr Uma operação bit a bit XOR . a ^ b a Xor b
ExclusiveOrAssign Uma operação de atribuição composta bit a bit XOR . a ^= b Não há suporte.
GreaterThan Uma comparação "maior que". a > b a > b
GreaterThanOrEqual Uma comparação "maior ou igual a". a >= b Não há suporte.
LeftShift Uma operação de deslocamento à esquerda bit a bit. a << b a << b
LeftShiftAssign Uma operação de atribuição composta de deslocamento esquerdo bit a bit. a <<= b Não há suporte.
LessThan Uma comparação "menor que". a < b a < b
LessThanOrEqual Uma comparação "menor ou igual a". a <= b Não há suporte.
Modulo Uma operação de restante aritmética. a % b a Mod b
ModuloAssign Uma operação de atribuição composta de resto aritmético. a %= b Não há suporte.
Multiply Uma operação de multiplicação sem verificação de estouro, para operandos numéricos. a * b a * b
MultiplyAssign Uma operação de atribuição composta de multiplicação sem verificação de estouro, para operandos numéricos. a *= b Não há suporte.
NotEqual Uma comparação de desigualdade. a != b a <> b
Or Uma operação lógica ou bit OR a bit. a &#124; b a Or b
OrAssign Uma atribuição composta bit a bit ou lógica OR . a &#124;= b Não há suporte.
Power Uma operação matemática de elevar um número a uma potência. Não há suporte. a ^ b
RightShift Uma operação de deslocamento bit a bit para a direita. a >> b a >> b
RightShiftAssign Uma operação de atribuição composta de deslocamento à direita bit a bit. a >>= b Não há suporte.
Subtract Uma operação de subtração sem verificação de estouro, para operandos numéricos. a - b a - b
SubtractAssign Uma operação de atribuição composta de subtração sem verificação de estouro, para operandos numéricos. a -= b Não há suporte.

Observação

Para implementar OrElse operações (a || b) e AndAlso (a && b) para objetos dinâmicos em C#, convém implementar o TryUnaryOperation método e o TryBinaryOperation método .

A OrElse operação consiste na operação unária IsTrue e na operação binária Or . A Or operação será executada somente se o resultado da IsTrue operação for false.

A AndAlso operação consiste na operação unária IsFalse e na operação binária And . A And operação será executada somente se o resultado da IsFalse operação for false.

Aplica-se a