DynamicObject.TryUnaryOperation(UnaryOperationBinder, Object) Méthode

Définition

Fournit l'implémentation pour les opérations unaires. 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 la négation, l'incrémentation ou la décrémentation.

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

Paramètres

binder
UnaryOperationBinder

Fournit des informations sur l'opération unaire. La binder.Operation propriété retourne un ExpressionType objet. Par exemple, pour l’instruction negativeNumber = -number , où number est dérivée de la DynamicObject classe, binder.Operation retourne « Negate ».

result
Object

Résultat de l'opération unaire.

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 une opération de négation mathématique 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 TryUnaryOperation méthode pour activer l’opération de négation mathématique. Is remplace également les TrySetMember méthodes et TryGetMember pour activer l’accès aux éléments.

Dans cet exemple, seule l’opération de négation mathématique est prise en charge. Si vous essayez d’écrire une instruction telle que negativeNumber = +number, une exception d’exécution se produit.

// 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 unary operation.
    public override bool TryUnaryOperation(
        UnaryOperationBinder binder, out object result)
    {
        // The Textual property contains
        // the name of the unary operation in addition
        // to the textual representaion of the number.
        string resultTextual =
             binder.Operation + " " +
             dictionary["Textual"].ToString();
        int resultNumeric;

        // Determining what type of operation is being performed.
        switch (binder.Operation)
        {
            case ExpressionType.Negate:
                resultNumeric =
                     -(int)dictionary["Numeric"];
                break;
            default:
                // In case of any other unary 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 +
                    ": This unary 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 number = new DynamicNumber();

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

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

        dynamic negativeNumber = new DynamicNumber();

        // Performing a mathematical negation.
        // TryUnaryOperation is called.
        negativeNumber = -number;

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

        // The following statement produces a run-time exception
        // because the unary plus operation is not implemented.
        // negativeNumber = +number;
    }
}

// This code example produces the following output:

// One 1
// Negate One -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 unary operation. 
    Public Overrides Function TryUnaryOperation(
        ByVal binder As System.Dynamic.UnaryOperationBinder,
        ByRef result As Object) As Boolean

        ' The Textual property contains the name of the unary operation
        ' in addition to the textual representaion of the number.
        Dim resultTextual As String =
        binder.Operation.ToString() & " " &
        dictionary("Textual")
        Dim resultNumeric As Integer

        ' Determining what type of operation is being performed.
        Select Case binder.Operation
            Case ExpressionType.Negate
                resultNumeric = -CInt(dictionary("Numeric"))
            Case Else
                ' In case of any other unary 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 unary 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 number As Object = New DynamicNumber()

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

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

    Dim negativeNumber As Object = New DynamicNumber()

    ' Performing a mathematical negation.
    ' The TryUnaryOperation is called.
    negativeNumber = -number

    Console.WriteLine(
        negativeNumber.Textual & " " & negativeNumber.Numeric)

    ' The following statement produces a run-time exception
    ' because the unary plus operation is not implemented.
    'negativeNumber = +number
End Sub

' This code example produces the following output:

' One 1
' Negate One -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 unaires 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 unaires telles que la négation, l’incrément ou la décrémentation. Par exemple, si la TryUnaryOperation méthode est remplacée, cette méthode est appelée automatiquement pour les instructions telles que negativeNumber = -number, où number est dérivée de la DynamicObject classe .

Vous pouvez obtenir des informations sur le type de l’opération unaire à 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
Decrement Opération de décrémentation unaire. a-- Non pris en charge.
Increment Opération d’incrémentation unaire. a++ Non pris en charge.
Negate Négation arithmétique. -a -a
Not Négation logique. !a Not a
OnesComplement Un complément. ~a Non pris en charge.
IsFalse Valeur de condition false. a && b Non pris en charge.
IsTrue Valeur de condition true. a &#124;&#124; b Non pris en charge.
UnaryPlus Un plus unaire. +a +a

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 à