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 从 类派生DynamicObject的 语句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 一个真正的条件值。 a &#124;&#124; b 不支持。
UnaryPlus 一元加号。 +a +a

注意

若要在 C# 中实现 OrElse (a || b) 和 AndAlso (a && b) 操作,可能需要同时 TryUnaryOperation 实现 方法和 TryBinaryOperation 方法。

OrElse 操作由一元 IsTrue 运算和二进制 Or 运算组成。 Or仅当操作的结果为 false时,IsTrue才会执行该操作。

AndAlso 操作由一元 IsFalse 运算和二进制 And 运算组成。 And仅当操作的结果为 false时,IsFalse才会执行该操作。

适用于