DynamicObject.TryUnaryOperation(UnaryOperationBinder, Object) Método

Definición

Proporciona la implementación de operaciones unarias. Las clases derivadas de la clase DynamicObject pueden invalidar este método para especificar el comportamiento dinámico de operaciones como negación, incremento o decremento.

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

Parámetros

binder
UnaryOperationBinder

Proporciona información sobre la operación unaria. La binder.Operation propiedad devuelve un ExpressionType objeto . Por ejemplo, para la negativeNumber = -number instrucción , donde number se deriva de la DynamicObject clase , binder.Operation devuelve "Negate".

result
Object

Resultado de la operación unaria.

Devoluciones

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

Ejemplos

Supongamos que necesita una estructura de datos para almacenar representaciones textuales y numéricas de números y desea definir una operación de negación matemática para dichos datos.

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

En este ejemplo, solo se admite la operación de negación matemática. Si intenta escribir una instrucción como negativeNumber = +number, 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 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

Comentarios

Las clases derivadas de la DynamicObject clase pueden invalidar este método para especificar cómo se deben realizar las operaciones unarias 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 inicia una excepción específica del lenguaje en tiempo de ejecución).

Se llama a este método cuando tiene operaciones unarias como negación, incremento o decremento. Por ejemplo, si el TryUnaryOperation método se invalida, este método se invoca automáticamente para instrucciones como negativeNumber = -number, donde number se deriva de la DynamicObject clase .

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

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

Valor Descripción C# Visual Basic
Decrement Una operación de decremento unario. a-- No se admite.
Increment Una operación de incremento unario. a++ No se admite.
Negate Negación aritmética. -a -a
Not Negación lógica. !a Not a
OnesComplement Uno complementa. ~a No se admite.
IsFalse Valor de condición false. a && b No se admite.
IsTrue Valor de condición true. a &#124;&#124; b No se admite.
UnaryPlus Un unario más. +a +a

Nota

Para implementar OrElse operaciones (a || b) y AndAlso (a && b) 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