DynamicObject.TryBinaryOperation Metoda
Definice
Důležité
Některé informace platí pro předběžně vydaný produkt, který se může zásadně změnit, než ho výrobce nebo autor vydá. Microsoft neposkytuje žádné záruky, výslovné ani předpokládané, týkající se zde uváděných informací.
Poskytuje implementaci binárních operací. Třídy odvozené z třídy mohou přepsat tuto metodu DynamicObject k určení dynamického chování operací, jako je sčítání a násobení.
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
Parametry
- binder
- BinaryOperationBinder
Poskytuje informace o binární operaci. Vlastnost binder.Operation vrátí ExpressionType objekt. Například pro sum = first + second příkaz, kde first a second jsou odvozeny z DynamicObject třídy, binder.Operation vrátí ExpressionType.Add.
- arg
- Object
Pravý operand binární operace. Například pro sum = first + second příkaz, kde first a second jsou odvozeny z DynamicObject třídy, arg je rovno second.
- result
- Object
Výsledek binární operace.
Návraty
trueje-li operace úspěšná; v opačném případě . false Pokud tato metoda vrátí false, run-time binder jazyka určuje chování. (Ve většině případů se vyvolá výjimka za běhu specifická pro jazyk.)
Příklady
Předpokládejme, že potřebujete datovou strukturu pro ukládání textových a číselných reprezentací čísel a chcete definovat základní matematické operace, jako je sčítání a odčítání těchto dat.
Následující příklad kódu ukazuje DynamicNumber třídu, která je odvozena z DynamicObject třídy.
DynamicNumber přepíše metodu TryBinaryOperation pro povolení matematických operací. Přepíše také metody TrySetMember a TryGetMember povolí přístup k prvkům.
V tomto příkladu jsou podporovány pouze operace sčítání a odčítání. Pokud se pokusíte napsat příkaz jako resultNumber = firstNumber*secondNumber, je vyvolán výjimka za běhu.
// 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
Poznámky
Třídy odvozené z DynamicObject třídy mohou přepsat tuto metodu určit, jak binární operace mají být provedeny pro dynamický objekt. Pokud metoda není přepsána, pořadač za běhu jazyka určuje chování. (Ve většině případů se vyvolá výjimka za běhu specifická pro jazyk.)
Tato metoda se volá, pokud máte binární operace, jako je sčítání nebo násobení. Pokud je například TryBinaryOperation metoda přepsána, je automaticky vyvolána pro příkazy jako sum = first + second nebo multiply = first*second, kde first je odvozen z DynamicObject třídy.
Informace o typu binární operace můžete získat pomocí Operation vlastnosti parametru binder .
Pokud se dynamický objekt používá pouze v jazyce C# a Visual Basic, vlastnost binder.Operation může mít jednu z následujících hodnot z výčtu ExpressionType. V jiných jazycích, jako je IronPython nebo IronRuby, ale můžete mít jiné hodnoty.
| Hodnota | Description | jazyk C# | Visual Basic |
|---|---|---|---|
Add |
Operace sčítání bez kontroly přetečení číselných operandů. | a + b |
a + b |
AddAssign |
Operace sčítání složeného přiřazení bez kontroly přetečení číselných operandů. | a += b |
Není podporováno. |
And |
Bitové AND operace. |
a & b |
a And b |
AndAssign |
Operace bitového AND složeného přiřazení. |
a &= b |
Není podporováno. |
Divide |
Aritmetická operace dělení. | a / b |
a / b |
DivideAssign |
Operace složeného přiřazení aritmetického dělení | a /= b |
Není podporováno. |
ExclusiveOr |
Bitové XOR operace. |
a ^ b |
a Xor b |
ExclusiveOrAssign |
Operace bitového XOR složeného přiřazení. |
a ^= b |
Není podporováno. |
GreaterThan |
Porovnání "větší než". | a > b |
a > b |
GreaterThanOrEqual |
Porovnání "větší než nebo rovno" | a >= b |
Není podporováno. |
LeftShift |
Bitové operace levého posunu. | a << b |
a << b |
LeftShiftAssign |
Operace složeného přiřazení s bitovým posunem doleva. | a <<= b |
Není podporováno. |
LessThan |
Porovnání "menší než". | a < b |
a < b |
LessThanOrEqual |
Porovnání "menší než nebo rovno" | a <= b |
Není podporováno. |
Modulo |
Aritmetická operace zbytku. | a % b |
a Mod b |
ModuloAssign |
Operace aritmetického zbytku složeného přiřazení | a %= b |
Není podporováno. |
Multiply |
Operace násobení bez kontroly přetečení číselných operandů. | a * b |
a * b |
MultiplyAssign |
Operace násobení složeného přiřazení bez kontroly přetečení číselných operandů. | a *= b |
Není podporováno. |
NotEqual |
Porovnání nerovnosti. | a != b |
a <> b |
Or |
Bitové nebo logické OR operace. |
a | b |
a Or b |
OrAssign |
Bitové nebo logické složené OR přiřazení. |
a |= b |
Není podporováno. |
Power |
Matematická operace zvýšení čísla na mocninu | Není podporováno. | a ^ b |
RightShift |
Bitové operace posunu doprava. | a >> b |
a >> b |
RightShiftAssign |
Bitové operace složeného přiřazení posunu doprava. | a >>= b |
Není podporováno. |
Subtract |
Operace odčítání bez kontroly přetečení číselných operandů. | a - b |
a - b |
SubtractAssign |
Operace odčítání složeného přiřazení bez kontroly přetečení číselných operandů. | a -= b |
Není podporováno. |
Note
Pokud chcete implementovat operace (OrElse) a a || b (AndAlso) pro dynamické objekty v jazyce C#, můžete chtít implementovat metodu a && b i metoduTryUnaryOperation.TryBinaryOperation
Operace OrElse se skládá z unární IsTrue operace a binární Or operace. Operace Or se provádí pouze v případě, že je výsledkem IsTrue operace false.
Operace AndAlso se skládá z unární IsFalse operace a binární And operace. Operace And se provádí pouze v případě, že je výsledkem IsFalse operace false.