Share via


DynamicObject.TryBinaryOperation Méthode

Définition

Fournit une implémentation pour les opérations binaires. Les classes dérivées de la classe DynamicObject peuvent substituer cette méthode afin de spécifier le comportement dynamique pour certaines opérations telles que l'addition et la multiplication.

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

Paramètres

binder
BinaryOperationBinder

Fournit des informations sur l'opération binaire. La binder.Operation propriété retourne un ExpressionType objet. Par exemple, pour l’instruction sum = first + second , où first et second sont dérivés de la DynamicObject classe , binder.Operation retourne ExpressionType.Add.

arg
Object

Opérande droit pour l'opération binaire. Par exemple, pour l’instruction sum = first + second , où first et second sont dérivés de la DynamicObject classe, arg est égal à second.

result
Object

Résultat de l'opération binaire.

Retours

true si l'opération réussit ; sinon false. Si cette méthode retourne false, le binder d'exécution du langage détermine le comportement. (Dans la plupart des cas, une exception runtime spécifique au langage est levée.)

Exemples

Supposons que vous avez besoin d’une structure de données pour stocker des représentations textuelles et numériques de nombres, et que vous souhaitez définir des opérations mathématiques de base telles que l’addition et la soustraction pour ces données.

L’exemple de code suivant illustre la DynamicNumber classe, qui est dérivée de la DynamicObject classe . DynamicNumber remplace la TryBinaryOperation méthode pour activer les opérations mathématiques. Il remplace également les TrySetMember méthodes et TryGetMember pour permettre l’accès aux éléments.

Dans cet exemple, seules les opérations d’addition et de soustraction sont prises en charge. Si vous essayez d’écrire une instruction telle que resultNumber = firstNumber*secondNumber, une exception d’exécution est levée.

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

Remarques

Les classes dérivées de la DynamicObject classe peuvent remplacer cette méthode pour spécifier la façon dont les opérations binaires doivent être effectuées pour un objet dynamique. Lorsque la méthode n’est pas remplacée, le classeur d’exécution du langage détermine le comportement. (Dans la plupart des cas, une exception runtime spécifique au langage est levée.)

Cette méthode est appelée lorsque vous avez des opérations binaires telles que l’ajout ou la multiplication. Par exemple, si la TryBinaryOperation méthode est remplacée, elle est appelée automatiquement pour les instructions telles que sum = first + second ou multiply = first*second, où first est dérivée de la DynamicObject classe .

Vous pouvez obtenir des informations sur le type de l’opération binaire à l’aide de la Operation propriété du binder paramètre .

Si votre objet dynamique est utilisé uniquement en C# et Visual Basic, la binder.Operation propriété peut avoir l’une des valeurs suivantes de l’énumération ExpressionType . Toutefois, dans d’autres langages tels que IronPython ou IronRuby, vous pouvez avoir d’autres valeurs.

Value Description C# Visual Basic
Add Opération d’ajout sans vérification de dépassement de capacité, pour les opérandes numériques. a + b a + b
AddAssign Opération d’affectation composée d’addition sans vérification de dépassement de capacité, pour les opérandes numériques. a += b Non pris en charge.
And Opération au niveau du AND bit. a & b a And b
AndAssign Opération d’affectation composée au niveau du AND bit. a &= b Non pris en charge.
Divide Opération de division arithmétique. a / b a / b
DivideAssign Opération d’affectation composée de division arithmétique. a /= b Non pris en charge.
ExclusiveOr Opération au niveau du XOR bit. a ^ b a Xor b
ExclusiveOrAssign Opération d’affectation composée au niveau du XOR bit. a ^= b Non pris en charge.
GreaterThan Comparaison « supérieure à ». a > b a > b
GreaterThanOrEqual Comparaison « supérieure ou égale à ». a >= b Non pris en charge.
LeftShift Opération de décalage de gauche au niveau du bit. a << b a << b
LeftShiftAssign Opération d’affectation composée de décalage gauche au niveau du bit. a <<= b Non pris en charge.
LessThan Comparaison « inférieure à ». a < b a < b
LessThanOrEqual Comparaison « inférieure ou égale à ». a <= b Non pris en charge.
Modulo Opération de reste arithmétique. a % b a Mod b
ModuloAssign Opération d’affectation composée de reste arithmétique. a %= b Non pris en charge.
Multiply Opération de multiplication sans vérification de dépassement de capacité, pour les opérandes numériques. a * b a * b
MultiplyAssign Opération d’affectation composée de multiplication sans vérification de dépassement de capacité, pour les opérandes numériques. a *= b Non pris en charge.
NotEqual Comparaison des inégalités. a != b a <> b
Or Opération au niveau du bit ou logique OR . a &#124; b a Or b
OrAssign Affectation composée au niveau du bit ou logique OR . a &#124;= b Non pris en charge.
Power Opération mathématique d’élévation d’un nombre à une puissance. Non pris en charge. a ^ b
RightShift Opération de décalage vers la droite au niveau du bit. a >> b a >> b
RightShiftAssign Opération d’affectation composée au niveau du bit à droite. a >>= b Non pris en charge.
Subtract Opération de soustraction sans vérification de dépassement de capacité, pour les opérandes numériques. a - b a - b
SubtractAssign Opération d’affectation composée de soustraction sans vérification de dépassement de capacité, pour les opérandes numériques. a -= b Non pris en charge.

Notes

Pour implémenter OrElse les opérations (a || b) et AndAlso (a && b) pour les objets dynamiques en C#, vous pouvez implémenter à la fois la TryUnaryOperation méthode et la TryBinaryOperation méthode.

L’opération OrElse se compose de l’opération unaire IsTrue et de l’opération binaire Or . L’opération Or n’est effectuée que si le résultat de l’opération IsTrue est false.

L’opération AndAlso se compose de l’opération unaire IsFalse et de l’opération binaire And . L’opération And n’est effectuée que si le résultat de l’opération IsFalse est false.

S’applique à