DynamicObject.TryUnaryOperation(UnaryOperationBinder, Object) Metodo

Definizione

Fornisce l'implementazione per le operazioni unarie. Le classi derivate dalla classe DynamicObject possono eseguire l'override di questo metodo per specificare il comportamento dinamico per operazioni quale negazione, 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

Parametri

binder
UnaryOperationBinder

Fornisce informazioni sull'operazione unaria. La binder.Operation proprietà restituisce un ExpressionType oggetto. Ad esempio, per l'istruzione negativeNumber = -numberDynamicObject, in cui number è derivata dalla classe, binder.Operation restituisce "Negate".

result
Object

Risultato dell'operazione unaria.

Restituisce

true se l'operazione riesce; in caso contrario, false. Se questo metodo restituisce false, il comportamento viene determinato dal gestore di associazione di runtime del linguaggio. Nella maggior parte dei casi viene generata un'eccezione di runtime specifica del linguaggio.

Esempio

Si supponga che sia necessaria una struttura di dati per archiviare rappresentazioni testuali e numeriche di numeri e si vuole definire un'operazione di negazione matematica per tali dati.

Nell'esempio DynamicObject di codice seguente viene illustrata la DynamicNumber classe, derivata dalla classe . DynamicNumber esegue l'override del TryUnaryOperation metodo per abilitare l'operazione di negazione matematica. Esegue anche l'override dei TrySetMember metodi e TryGetMember per abilitare l'accesso agli elementi.

In questo esempio è supportata solo l'operazione di negazione matematica. Se si tenta di scrivere un'istruzione come negativeNumber = +number, si verifica un'eccezione di runtime.

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

Commenti

Le classi derivate dalla classe possono eseguire l'override DynamicObject di questo metodo per specificare la modalità di esecuzione delle operazioni unarie per un oggetto dinamico. Quando il metodo non viene sottoposto a override, il binder di runtime del linguaggio determina il comportamento. Nella maggior parte dei casi viene generata un'eccezione di runtime specifica del linguaggio.

Questo metodo viene chiamato quando si hanno operazioni unarie, ad esempio negazione, incremento o decremento. Ad esempio, se il TryUnaryOperation metodo viene sottoposto a override, questo metodo viene richiamato automaticamente per le istruzioni come negativeNumber = -number, dove number deriva dalla DynamicObject classe .

È possibile ottenere informazioni sul tipo dell'operazione unaria usando la Operation proprietà del binder parametro.

Se l'oggetto dinamico viene usato solo in C# e Visual Basic, la binder.Operation proprietà può avere uno dei valori seguenti dell'enumerazione ExpressionType . Tuttavia, in altre lingue, ad esempio IronPython o IronRuby, è possibile avere altri valori.

Valore Descrizione C# Visual Basic
Decrement Operazione di decremento unario. a-- Non supportata.
Increment Operazione di incremento unario. a++ Non supportata.
Negate Negazione aritmetica. -a -a
Not Negazione logica. !a Not a
OnesComplement Un complemento. ~a Non supportata.
IsFalse Valore di condizione false. a && b Non supportata.
IsTrue Valore della condizione true. a &#124;&#124; b Non supportata.
UnaryPlus Un plus unario. +a +a

Nota

Per implementare operazioni () e AndAlso (a || ba && b) per oggetti dinamici in C#, è possibile implementare OrElse sia il metodo che il TryBinaryOperationTryUnaryOperation metodo.

L'operazione OrElse è costituita dall'operazione unaria IsTrue e dall'operazione binaria Or . L'operazione Or viene eseguita solo se il risultato dell'operazione IsTrue è false.

L'operazione AndAlso è costituita dall'operazione unaria IsFalse e dall'operazione binaria And . L'operazione And viene eseguita solo se il risultato dell'operazione IsFalse è false.

Si applica a