DynamicObject.TryUnaryOperation(UnaryOperationBinder, Object) Метод

Определение

Предоставляет реализацию для унарных операций. Классы, производные от класса DynamicObject, могут переопределять этот метод, чтобы задать динамическое поведение для таких операций, как вычитание, увеличение или уменьшение.

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

Параметры

binder
UnaryOperationBinder

Предоставляет сведения об унарной операции. Свойство binder.Operation возвращает ExpressionType объект . Например, для negativeNumber = -number оператора , где number является производным DynamicObject от класса , binder.Operation возвращает значение "Negate".

result
Object

Результат унарной операции.

Возвращаемое значение

Значение true, если операция выполнена успешно; в противном случае — значение false. Если данный метод возвращает значение false, поведение определяется связывателем среды языка. (В большинстве случаев создается языковое исключение во время выполнения).

Примеры

Предположим, что для хранения текстовых и числовых представлений чисел требуется структура данных, и вы хотите определить для таких данных математическую операцию отрицания.

В следующем примере кода демонстрируется DynamicNumber класс , производный DynamicObject от класса . DynamicNumber переопределяет метод для TryUnaryOperation включения математической операции отрицания. Также переопределяет методы TrySetMember и TryGetMember , чтобы разрешить доступ к элементам.

В этом примере поддерживается только математическая операция отрицания. При попытке написать такой оператор, как negativeNumber = +number, возникает исключение во время выполнения.

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

Комментарии

Классы, производные от класса , DynamicObject могут переопределить этот метод, чтобы указать, как должны выполняться унарные операции для динамического объекта. Если метод не переопределен, поведение определяется связывателем времени выполнения языка. (В большинстве случаев создается языковое исключение во время выполнения).

Этот метод вызывается при наличии унарных операций, таких как отрицание, приращение или декремент. Например, если TryUnaryOperation метод переопределен, этот метод автоматически вызывается для таких операторов, как negativeNumber = -number, где number является производным DynamicObject от класса .

Сведения о типе унарной операции можно получить с помощью Operation свойства binder параметра .

Если динамический объект используется только в C# и Visual Basic, binder.Operation свойство может иметь одно из следующих значений перечисления ExpressionType . Однако в других языках, таких как IronPython или IronRuby, можно использовать и другие значения.

Значение Описание C# Visual Basic
Decrement Унарная операция декремента. a-- Не поддерживается.
Increment Операция унарного приращения. a++ Не поддерживается.
Negate Арифметическое отрицание. -a -a
Not Логическое отрицание. !a Not a
OnesComplement Дополнение к единицам. ~a Не поддерживается.
IsFalse Значение ложного условия. a && b Не поддерживается.
IsTrue Истинное значение условия. a &#124;&#124; b Не поддерживается.
UnaryPlus Унарный плюс. +a +a

Примечание

Для реализации OrElse операций (a || b) и AndAlso (a && b) для динамических объектов в C# может потребоваться реализовать как метод, TryUnaryOperation так и TryBinaryOperation метод .

Операция OrElse состоит из унарной IsTrue и двоичной Or операции. Операция Or выполняется только в том случае, если результатом IsTrue операции является false.

Операция AndAlso состоит из унарной IsFalse и двоичной And операции. Операция And выполняется только в том случае, если результатом IsFalse операции является false.

Применяется к