DynamicObject.TryBinaryOperation Método

Definición

Proporciona implementación para operaciones binarias. Las clases derivadas de la DynamicObject clase pueden invalidar este método para especificar el comportamiento dinámico de las operaciones, como la suma y la multiplicación.

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);
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

Proporciona información sobre la operación binaria. La binder.Operation propiedad devuelve un ExpressionType objeto . Por ejemplo, para la sum = first + second instrucción , donde first y second se derivan de la DynamicObject clase , binder.Operation devuelve ExpressionType.Add.

arg
Object

Operando derecho para la operación binaria. Por ejemplo, para la sum = first + second instrucción , donde first y second se derivan de la DynamicObject clase , arg es igual a second.

result
Object

Resultado de la operación binaria.

Devoluciones

true si la operación es correcta; de lo contrario, false. Si este método devuelve false, el enlazador en tiempo de ejecución del lenguaje determina el comportamiento. (En la mayoría de los casos, se produce una excepción en tiempo de ejecución específica del lenguaje).

Ejemplos

Supongamos que necesita una estructura de datos para almacenar representaciones textuales y numéricas de números, y desea definir operaciones matemáticas básicas, como la suma y la resta de dichos datos.

En el ejemplo de código siguiente se muestra la DynamicNumber clase , que se deriva de la DynamicObject clase . DynamicNumber invalida el TryBinaryOperation método para habilitar las operaciones matemáticas. También invalida los TrySetMember métodos y TryGetMember para habilitar el acceso a los elementos.

En este ejemplo, solo se admiten las operaciones de suma y resta. Si intenta escribir una instrucción como resultNumber = firstNumber*secondNumber, se produce una excepción en tiempo de ejecución.

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

Comentarios

Las clases derivadas de la DynamicObject clase pueden invalidar este método para especificar cómo se deben realizar las operaciones binarias para un objeto dinámico. Cuando el método no se invalida, el enlazador en tiempo de ejecución del lenguaje determina el comportamiento. (En la mayoría de los casos, se produce una excepción en tiempo de ejecución específica del lenguaje).

Se llama a este método cuando tiene operaciones binarias como suma o multiplicación. Por ejemplo, si el TryBinaryOperation método se invalida, se invoca automáticamente para instrucciones como sum = first + second o multiply = first*second, donde first se deriva de la DynamicObject clase .

Puede obtener información sobre el tipo de la operación binaria mediante la Operation propiedad del binder parámetro .

Si el objeto dinámico solo se usa en C# y Visual Basic, la propiedad binder.Operation puede tener uno de los valores siguientes de la enumeración ExpressionType. Sin embargo, en otros lenguajes, como IronPython o IronRuby, puede tener otros valores.

Value Descripción C# Visual Basic
Add Operación de suma sin comprobación de desbordamiento, para operandos numéricos. a + b a + b
AddAssign Una operación de asignación compuesta adicional sin comprobación de desbordamiento, para operandos numéricos. a += b No está soportado.
And Una operación bit a bit AND . a & b a And b
AndAssign Una operación de asignación compuesta bit a bit AND . a &= b No está soportado.
Divide Operación de división aritmética. a / b a / b
DivideAssign Una operación de asignación compuesta de división aritmética. a /= b No está soportado.
ExclusiveOr Una operación bit a bit XOR . a ^ b a Xor b
ExclusiveOrAssign Una operación de asignación compuesta bit a bit XOR . a ^= b No está soportado.
GreaterThan Una comparación "mayor que". a > b a > b
GreaterThanOrEqual Comparación "mayor o igual que". a >= b No está soportado.
LeftShift Operación de desplazamiento a la izquierda bit a bit. a << b a << b
LeftShiftAssign Una operación de asignación compuesta de desplazamiento a la izquierda bit a bit. a <<= b No está soportado.
LessThan Una comparación "menor que". a < b a < b
LessThanOrEqual Comparación de "menor o igual que". a <= b No está soportado.
Modulo Una operación de resto aritmético. a % b a Mod b
ModuloAssign Una operación de asignación compuesta de resto aritmético. a %= b No está soportado.
Multiply Una operación de multiplicación sin comprobación de desbordamiento, para operandos numéricos. a * b a * b
MultiplyAssign Una operación de asignación compuesta de multiplicación sin comprobación de desbordamiento, para operandos numéricos. a *= b No está soportado.
NotEqual Comparación de desigualdad. a != b a <> b
Or Una operación bit a bit o lógica OR . a &#124; b a Or b
OrAssign Asignación compuesta bit a bit o lógica OR . a &#124;= b No está soportado.
Power Una operación matemática de elevar un número a una potencia. No está soportado. a ^ b
RightShift Una operación de desplazamiento a la derecha bit a bit. a >> b a >> b
RightShiftAssign Una operación de asignación compuesta de desplazamiento a la derecha bit a bit. a >>= b No está soportado.
Subtract Operación de resta sin comprobación de desbordamiento para operandos numéricos. a - b a - b
SubtractAssign Una operación de asignación compuesta de resta sin comprobación de desbordamiento, para operandos numéricos. a -= b No está soportado.

Note

Para implementar OrElse (a || b) y AndAlso (a && b) operaciones para objetos dinámicos en C#, es posible que desee implementar el TryUnaryOperation método y el TryBinaryOperation método .

La OrElse operación consta de la operación unaria IsTrue y de la operación binaria Or . La Or operación solo se realiza si el resultado de la IsTrue operación es false.

La AndAlso operación consta de la operación unaria IsFalse y de la operación binaria And . La And operación solo se realiza si el resultado de la IsFalse operación es false.

Se aplica a