DynamicObject.TryBinaryOperation Metódus
Definíció
Fontos
Egyes információk olyan, kiadás előtti termékekre vonatkoznak, amelyek a kiadásig még jelentősen módosulhatnak. A Microsoft nem vállal kifejezett vagy törvényi garanciát az itt megjelenő információért.
Bináris műveletek implementálását biztosítja. Az osztályból származó osztályok felülbírálhatják ezt a DynamicObject metódust, hogy dinamikus viselkedést adjanak meg az olyan műveletekhez, mint az összeadás és a szorzás.
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
Paraméterek
- binder
- BinaryOperationBinder
Információt nyújt a bináris műveletről. A binder.Operation tulajdonság egy objektumot ExpressionType ad vissza. Például az sum = first + second utasítás esetében, ahol first és second amelyek az osztályból származnak, DynamicObject a binder.Operation visszaadott ExpressionType.Addértéket adja vissza.
- arg
- Object
A bináris művelet megfelelő operandusa. Például az sum = first + second utasítás esetében, ahol first és second amelyek az DynamicObject osztályból származnak, arg egyenlő a second.
- result
- Object
A bináris művelet eredménye.
Válaszok
trueha a művelet sikeres; egyéb esetben. false Ha ez a metódus visszatér false, a nyelv futásidejű kötése határozza meg a viselkedést. (A legtöbb esetben a rendszer nyelvspecifikus futásidejű kivételt ad ki.)
Példák
Tegyük fel, hogy szüksége van egy adatstruktúrára a számok szöveges és numerikus ábrázolásának tárolásához, és olyan alapvető matematikai műveleteket szeretne definiálni, mint például az adatok összeadása és kivonása.
Az alábbi példakód az DynamicNumber osztályból DynamicObject származtatott osztályt mutatja be.
DynamicNumber felülbírálja a metódust a TryBinaryOperation matematikai műveletek engedélyezéséhez. Felülbírálja az TrySetMember elemekhez való hozzáférést lehetővé tevő módszereket és TryGetMember módszereket is.
Ebben a példában csak az összeadási és kivonási műveletek támogatottak. Ha egy ilyen resultNumber = firstNumber*secondNumberutasítást próbál meg írni, a rendszer futásidejű kivételt jelez.
// 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
Megjegyzések
Az osztályból származó osztályok felülbírálhatják ezt a DynamicObject metódust, hogy megadják, hogyan kell bináris műveleteket végrehajtani egy dinamikus objektumon. Ha a metódus nincs felülírva, a nyelv futásidejű kötése határozza meg a viselkedést. (A legtöbb esetben a rendszer nyelvspecifikus futásidejű kivételt ad ki.)
Ezt a metódust akkor hívjuk meg, ha bináris műveleteket, például összeadást vagy szorzást hajt végre. Ha például a TryBinaryOperation metódus felül van bírálva, a rendszer automatikusan meghívja az olyan utasításokra, mint sum = first + second az vagy multiply = first*second, ahol first az DynamicObject osztályból származik.
A bináris művelet Operation típusáról a paraméter tulajdonságával binder kaphat információt.
Ha a dinamikus objektumot csak C# és Visual Basic használja, a binder.Operation tulajdonság a ExpressionType enumerálás alábbi értékeinek egyikével rendelkezhet. Más nyelvekben, például az IronPythonban vagy az IronRubyban azonban más értékek is lehetnek.
| Érték | Leírás | C# | Visual Basic |
|---|---|---|---|
Add |
Túlcsordulás ellenőrzése nélküli összeadási művelet numerikus operandusok esetén. | a + b |
a + b |
AddAssign |
Összetett hozzárendelési művelet túlcsordulás ellenőrzése nélkül numerikus operandusok esetén. | a += b |
Nem támogatott. |
And |
Bitenkénti AND művelet. |
a & b |
a And b |
AndAssign |
Bitenkénti AND összetett hozzárendelési művelet. |
a &= b |
Nem támogatott. |
Divide |
Aritmetikai osztási művelet. | a / b |
a / b |
DivideAssign |
Aritmetikai osztás összetett hozzárendelési művelete. | a /= b |
Nem támogatott. |
ExclusiveOr |
Bitenkénti XOR művelet. |
a ^ b |
a Xor b |
ExclusiveOrAssign |
Bitenkénti XOR összetett hozzárendelési művelet. |
a ^= b |
Nem támogatott. |
GreaterThan |
"Nagyobb, mint" összehasonlítás. | a > b |
a > b |
GreaterThanOrEqual |
"Nagyobb vagy egyenlő" összehasonlítás. | a >= b |
Nem támogatott. |
LeftShift |
Egy bitenkénti baleltolásos művelet. | a << b |
a << b |
LeftShiftAssign |
Egy bitenkénti bal műszakos összetett hozzárendelési művelet. | a <<= b |
Nem támogatott. |
LessThan |
"Kisebb, mint" összehasonlítás. | a < b |
a < b |
LessThanOrEqual |
"Kisebb vagy egyenlő" összehasonlítás. | a <= b |
Nem támogatott. |
Modulo |
Aritmetikai fennmaradó művelet. | a % b |
a Mod b |
ModuloAssign |
Aritmetikai fennmaradó összetett hozzárendelési művelet. | a %= b |
Nem támogatott. |
Multiply |
Túlcsordulás ellenőrzése nélküli szorzási művelet numerikus operandusok esetén. | a * b |
a * b |
MultiplyAssign |
Többszörös összetett hozzárendelési művelet túlcsordulás ellenőrzése nélkül numerikus operandusok esetén. | a *= b |
Nem támogatott. |
NotEqual |
Egy egyenlőtlenség-összehasonlítás. | a != b |
a <> b |
Or |
Bitenkénti vagy logikai OR művelet. |
a | b |
a Or b |
OrAssign |
Bitenkénti vagy logikai OR összetett hozzárendelés. |
a |= b |
Nem támogatott. |
Power |
Egy szám hatványra emelésének matematikai művelete. | Nem támogatott. | a ^ b |
RightShift |
Egy bitenkénti jobb műszakos művelet. | a >> b |
a >> b |
RightShiftAssign |
Bitenkénti jobb műszakos összetett hozzárendelési művelet. | a >>= b |
Nem támogatott. |
Subtract |
Túlcsordulás ellenőrzése nélküli kivonási művelet numerikus operandusok esetén. | a - b |
a - b |
SubtractAssign |
Kivonási összetett hozzárendelési művelet túlcsordulás ellenőrzése nélkül numerikus operandusok esetén. | a -= b |
Nem támogatott. |
Note
A C# dinamikus objektumainak (OrElse) és a || b (AndAlso) műveleteinek implementálásához a && b érdemes lehet a metódust és a TryUnaryOperation metódust TryBinaryOperation is implementálni.
A OrElse művelet a nem naplós IsTrue műveletből és a bináris Or műveletből áll. A Or műveletet csak akkor hajtja végre, ha a IsTrue művelet eredménye .false
A AndAlso művelet a nem naplós IsFalse műveletből és a bináris And műveletből áll. A And műveletet csak akkor hajtja végre, ha a IsFalse művelet eredménye .false