DynamicObject.TryBinaryOperation 方法

定義

提供二進位運算的實作。 衍生自 DynamicObject 類別的類別可以覆寫這個方法,以指定加法和乘法這類運算的動態行為。

public:
 virtual bool TryBinaryOperation(System::Dynamic::BinaryOperationBinder ^ binder, System::Object ^ arg, [Runtime::InteropServices::Out] System::Object ^ % result);
public virtual bool TryBinaryOperation (System.Dynamic.BinaryOperationBinder binder, object arg, out object result);
public virtual bool TryBinaryOperation (System.Dynamic.BinaryOperationBinder binder, object arg, out object? result);
abstract member TryBinaryOperation : System.Dynamic.BinaryOperationBinder * obj * obj -> bool
override this.TryBinaryOperation : System.Dynamic.BinaryOperationBinder * obj * obj -> bool
Public Overridable Function TryBinaryOperation (binder As BinaryOperationBinder, arg As Object, ByRef result As Object) As Boolean

參數

binder
BinaryOperationBinder

提供二進位運算的相關資訊。 屬性會 binder.OperationExpressionType 回 物件。 例如,針對 sum = first + second 語句,其中 firstsecond 衍生自 DynamicObject 類別, binder.Operation 會傳 ExpressionType.Add 回 。

arg
Object

二進位運算的右運算元。 例如,針對 sum = first + second 語句,其中 firstsecond 衍生自 DynamicObject 類別, arg 等於 second

result
Object

二進位運算的結果。

傳回

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

範例

假設您需要資料結構來儲存數位的文字和數值表示,而且您想要定義基本的數學運算,例如這類資料的加法和減法。

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

在此範例中,僅支援加法和減法運算。 如果您嘗試撰寫類似 resultNumber = firstNumber*secondNumber 的語句,則會擲回運行時例外狀況。

// 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 binary operation.
    public override bool TryBinaryOperation(
        BinaryOperationBinder binder, object arg, out object result)
    {
        // The Textual property contains the textual representaion
        // of two numbers, in addition to the name
        // of the binary operation.
        string resultTextual =
            dictionary["Textual"].ToString() + " "
            + binder.Operation + " " +
            ((DynamicNumber)arg).dictionary["Textual"].ToString();

        int resultNumeric;

        // Checking what type of operation is being performed.
        switch (binder.Operation)
        {
            // Proccessing mathematical addition (a + b).
            case ExpressionType.Add:
                resultNumeric =
                    (int)dictionary["Numeric"] +
                    (int)((DynamicNumber)arg).dictionary["Numeric"];
                break;

            // Processing mathematical substraction (a - b).
            case ExpressionType.Subtract:
                resultNumeric =
                    (int)dictionary["Numeric"] -
                    (int)((DynamicNumber)arg).dictionary["Numeric"];
                break;

            // In case of any other binary 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.)
            default:
                Console.WriteLine(
                    binder.Operation +
                    ": This binary 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 firstNumber = new DynamicNumber();

        // Creating properties and setting their values
        // for the first dynamic number.
        // The TrySetMember method is called.
        firstNumber.Textual = "One";
        firstNumber.Numeric = 1;

        // Printing out properties. The TryGetMember method is called.
        Console.WriteLine(
            firstNumber.Textual + " " + firstNumber.Numeric);

        // Creating the second dynamic number.
        dynamic secondNumber = new DynamicNumber();
        secondNumber.Textual = "Two";
        secondNumber.Numeric = 2;
        Console.WriteLine(
            secondNumber.Textual + " " + secondNumber.Numeric);

        dynamic resultNumber = new DynamicNumber();

        // Adding two numbers. The TryBinaryOperation is called.
        resultNumber = firstNumber + secondNumber;

        Console.WriteLine(
            resultNumber.Textual + " " + resultNumber.Numeric);

        // Subtracting two numbers. TryBinaryOperation is called.
        resultNumber = firstNumber - secondNumber;

        Console.WriteLine(
            resultNumber.Textual + " " + resultNumber.Numeric);

        // The following statement produces a run-time exception
        // because the multiplication operation is not implemented.
        // resultNumber = firstNumber * secondNumber;
    }
}

// This code example produces the following output:

// One 1
// Two 2
// One Add Two 3
// One Subtract Two -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 binary operation. 
    Public Overrides Function TryBinaryOperation(
        ByVal binder As System.Dynamic.BinaryOperationBinder,
        ByVal arg As Object, ByRef result As Object) As Boolean

        ' The Textual property contains the textual representaion 
        ' of two numbers, in addition to the name of the binary operation.
        Dim resultTextual As String =
            dictionary("Textual") & " " &
            binder.Operation.ToString() & " " &
        CType(arg, DynamicNumber).dictionary("Textual")

        Dim resultNumeric As Integer

        ' Checking what type of operation is being performed.
        Select Case binder.Operation
            ' Proccessing mathematical addition (a + b).
            Case ExpressionType.Add
                resultNumeric =
                CInt(dictionary("Numeric")) +
                CInt((CType(arg, DynamicNumber)).dictionary("Numeric"))

                ' Processing mathematical substraction (a - b).
            Case ExpressionType.Subtract
                resultNumeric =
                CInt(dictionary("Numeric")) -
                CInt((CType(arg, DynamicNumber)).dictionary("Numeric"))

            Case Else
                ' In case of any other binary 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 binary 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 firstNumber As Object = New DynamicNumber()

    ' Creating properties and setting their values
    ' for the first dynamic number. 
    ' The TrySetMember method is called.
    firstNumber.Textual = "One"
    firstNumber.Numeric = 1

    ' Printing out properties. The TryGetMember method is called.
    Console.WriteLine(
        firstNumber.Textual & " " & firstNumber.Numeric)

    ' Creating the second dynamic number.
    Dim secondNumber As Object = New DynamicNumber()
    secondNumber.Textual = "Two"
    secondNumber.Numeric = 2
    Console.WriteLine(
        secondNumber.Textual & " " & secondNumber.Numeric)

    Dim resultNumber As Object = New DynamicNumber()

    ' Adding two numbers. TryBinaryOperation is called.
    resultNumber = firstNumber + secondNumber
    Console.WriteLine(
        resultNumber.Textual & " " & resultNumber.Numeric)

    ' Subtracting two numbers. TryBinaryOperation is called.
    resultNumber = firstNumber - secondNumber
    Console.WriteLine(
        resultNumber.Textual & " " & resultNumber.Numeric)

    ' The following statement produces a run-time exception
    ' because the multiplication operation is not implemented.
    ' resultNumber = firstNumber * secondNumber
End Sub

' This code example produces the following output:

' One 1
' Two 2
' One Add Two 3
' One Subtract Two -1

備註

衍生自 類別的 DynamicObject 類別可以覆寫這個方法,以指定動態物件應如何執行二進位作業。 未覆寫方法時,語言的執行時間系結器會決定行為。 (在大多數情況下,將會擲回特定語言的執行階段例外狀況)。

當您有加法或乘法等二進位運算時,就會呼叫這個方法。 例如,如果 TryBinaryOperation 覆寫 方法,系統會自動針對 或 multiply = first*second 之類的 sum = first + second 語句叫用此方法,其中 first 衍生自 DynamicObject 類別。

您可以使用 參數的 binder 屬性,取得二進位作業 Operation 類型的相關資訊。

如果您的動態物件只用于 C# 和 Visual Basic 中, binder.Operation 則 屬性可以從 列舉中取得下列其中一個值 ExpressionType 。 不過,在 IronPython 或 IronRuby 等其他語言中,您可以有其他值。

描述 C# Visual Basic
Add 數值運算元沒有溢位檢查的加法運算。 a + b a + b
AddAssign 數值運算元沒有溢位檢查的加法複合指派運算。 a += b 不支援。
And AND 運算。 a & b a And b
AndAssign AND 複合指派作業。 a &= b 不支援。
Divide 算術除法運算。 a / b a / b
DivideAssign 算術除法複合指派運算。 a /= b 不支援。
ExclusiveOr XOR 運算。 a ^ b a Xor b
ExclusiveOrAssign XOR 複合指派作業。 a ^= b 不支援。
GreaterThan 「大於」比較。 a > b a > b
GreaterThanOrEqual 「大於或等於」比較。 a >= b 不支援。
LeftShift 位左移運算。 a << b a << b
LeftShiftAssign 位左移複合指派作業。 a <<= b 不支援。
LessThan 「小於」比較。 a < b a < b
LessThanOrEqual 「小於或等於」比較。 a <= b 不支援。
Modulo 算術餘數運算。 a % b a Mod b
ModuloAssign 算術餘數複合指派運算。 a %= b 不支援。
Multiply 數值運算元的乘法運算,不含溢位檢查。 a * b a * b
MultiplyAssign 數值運算元的乘法複合指派運算,不含溢位檢查。 a *= b 不支援。
NotEqual 不等比較。 a != b a <> b
Or 位或邏輯 OR 運算。 a &#124; b a Or b
OrAssign 位或邏輯 OR 複合指派。 a &#124;= b 不支援。
Power 將數位提升為乘冪的數學運算。 不支援。 a ^ b
RightShift 位右移運算。 a >> b a >> b
RightShiftAssign 位右移複合指派作業。 a >>= b 不支援。
Subtract 數值運算元沒有溢位檢查的減法運算。 a - b a - b
SubtractAssign 數值運算元沒有溢位檢查的減法複合指派運算。 a -= b 不支援。

注意

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

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

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

適用於