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);
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.Operation возвращает ExpressionType объект . Например, для инструкции sum = first + second , где first и second извлекаются из DynamicObject класса, binder.Operation возвращается ExpressionType.Add.
- arg
- Object
Правый операнд для двоичной операции. Например, для инструкции sum = first + second , где first и second производные от DynamicObject класса, arg равны second.
- result
- Object
Результат двоичной операции.
Возвращаемое значение
Значение true, если операция выполнена успешно; в противном случае — значение false. Если этот метод возвращает false, привязка во время выполнения языка определяет поведение. (В большинстве случаев создается исключение времени выполнения для конкретного языка.)
Примеры
Предположим, что требуется структура данных для хранения текстовых и числовых представлений чисел, и необходимо определить основные математические операции, такие как добавление и вычитание для таких данных.
В следующем примере кода демонстрируется класс, производный DynamicNumber от DynamicObject класса.
DynamicNumber переопределяет TryBinaryOperation метод для включения математических операций. Он также переопределяет TrySetMember методы и TryGetMember методы, позволяющие получить доступ к элементам.
В этом примере поддерживаются только операции сложения и вычитания. При попытке написать инструкцию, например 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 метод переопределен, он автоматически вызывается для операторов, таких sum = first + second как или multiply = first*second, где first является производным DynamicObject от класса.
Вы можете получить сведения о типе двоичной операции с помощью Operation свойства binder параметра.
Если динамический объект используется только в 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 | b |
a Or b |
OrAssign |
Побитовое или логическое OR составное назначение. |
a |= b |
Не поддерживается. |
Power |
Математическая операция повышения числа к власти. | Не поддерживается. | a ^ b |
RightShift |
Побитовая операция сдвига вправо. | a >> b |
a >> b |
RightShiftAssign |
Побитовая операция назначения вправо. | a >>= b |
Не поддерживается. |
Subtract |
Операция вычитания без проверки переполнения для числовых операндов. | a - b |
a - b |
SubtractAssign |
Операция вычитания составного назначения без проверки переполнения для числовых операндов. | a -= b |
Не поддерживается. |
Note
Для реализации операций (a || b) и (a && b) для динамических объектов в C#может потребоваться реализовать OrElse как метод, так TryUnaryOperation и TryBinaryOperationAndAlso метод.
Операция OrElse состоит из унарной операции и двоичной IsTrueOr операции. Операция Or выполняется только в том случае, если результат IsTrue операции .false
Операция AndAlso состоит из унарной операции и двоичной IsFalseAnd операции. Операция And выполняется только в том случае, если результат IsFalse операции .false