共用方式為


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.OperationExpressionType 回物件。 例如,針對衍生自 類別的 negativeNumber = -numberDynamicObject 語句numberbinder.Operation會傳回 「Negate」。。

result
Object

一元運算的結果。

傳回

如果作業成功,則為 true,否則為 false。 如果這個方法傳回 false,語言的執行階段繫結器會決定行為。 (在大多數情況下,將會擲回特定語言的執行階段例外狀況)。

範例

假設您需要數據結構來儲存數位的文字和數值表示,而且您想要定義這類數據的數學否定運算。

下列程式代碼範例示範 DynamicNumber 衍生自 類別的 DynamicObject 類別。 DynamicNumberTryUnaryOperation 覆寫 方法,以啟用數學否定運算。 也會覆寫 TrySetMemberTryGetMember 方法,以啟用元素的存取權。

在此範例中,只支援數學否定運算。 如果您嘗試撰寫類似 的 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 類別。

您可以使用 參數的 binder 屬性,取得一元運算Operation類型的相關信息。

如果您的動態物件只用於 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 false 條件值。 a && b 不支援。
IsTrue true 條件值。 a &#124;&#124; b 不支援。
UnaryPlus 一元加號。 +a +a

注意

若要在 C# 中實 OrElse 作動態物件的 (a || b) 和 AndAlso (a && b) 作業,您可以同時實 TryUnaryOperation 作 方法和 TryBinaryOperation 方法。

OrElse 作業是由一元 IsTrue 運算和二進位 Or 運算所組成。 Or只有在作業的結果IsTruefalse時,才會執行作業。

AndAlso 作業是由一元 IsFalse 運算和二進位 And 運算所組成。 And只有在作業的結果IsFalsefalse時,才會執行作業。

適用於