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 대해 여기서 number 는 클래스에서 DynamicObject 파생되며 는 binder.Operation "Negate"를 반환합니다.

result
Object

단항 연산의 결과입니다.

반환

작업에 성공하면 true이고, 그렇지 않으면 false입니다. 이 메서드가 false를 반환하는 경우 언어의 런타임 바인더에 따라 동작이 결정됩니다. 대부분의 경우 언어별 런타임 예외가 throw됩니다.

예제

숫자의 텍스트 및 숫자 표현을 저장하기 위해 데이터 구조가 필요하고 이러한 데이터에 대한 수학 부정 연산을 정의하려고 한다고 가정합니다.

다음 코드 예제에서는 DynamicNumber 클래스에서 파생 된 클래스를 보여 줍니다 DynamicObject . DynamicNumber 는 메서드를 재정의 TryUnaryOperation 하여 수학 부정 연산을 사용하도록 설정합니다. 또한 요소에 TrySetMember 액세스할 수 있도록 및 TryGetMember 메서드를 재정의합니다.

이 예제에서는 수학 부정 연산만 지원됩니다. 와 같은 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 하여 동적 개체에 대해 단항 연산을 수행하는 방법을 지정할 수 있습니다. 메서드를 재정의하지 않으면 언어의 런타임 바인더가 동작을 결정합니다. 대부분의 경우 언어별 런타임 예외가 throw됩니다.

이 메서드는 부정, 증가 또는 감소와 같은 단항 연산이 있을 때 호출됩니다. 예를 들어 메서드를 재정의 TryUnaryOperation 하는 경우 이 메서드는 와 같은 negativeNumber = -number문에 대해 자동으로 호출됩니다. 여기서 number 는 클래스에서 DynamicObject 파생됩니다.

매개 변수의 속성을 사용하여 Operation 단항 연산의 binder 형식에 대한 정보를 가져올 수 있습니다.

동적 개체가 C# 및 Visual Basic에서만 사용되는 경우 속성은 binder.Operation 열거형의 ExpressionType 다음 값 중 하나를 가질 수 있습니다. 그러나 IronPython 또는 IronRuby와 같은 다른 언어에서는 다른 값을 가질 수 있습니다.

Description C# Visual Basic
Decrement 단항 감소 작업입니다. a-- 지원되지 않습니다.
Increment 단항 증분 작업입니다. a++ 지원되지 않습니다.
Negate 산술 부정입니다. -a -a
Not 논리적 부정입니다. !a Not a
OnesComplement 보완합니다. ~a 지원되지 않습니다.
IsFalse false 조건 값입니다. a && b 지원되지 않습니다.
IsTrue true 조건 값입니다. a &#124;&#124; b 지원되지 않습니다.
UnaryPlus 단항 플러스. +a +a

참고

C#에서 동적 개체에 대한 (a || b) 및 AndAlso (a && b) 작업을 구현 OrElse 하려면 메서드와 TryBinaryOperation 메서드를 TryUnaryOperation 모두 구현하는 것이 좋습니다.

작업은 OrElse 단항 IsTrue 연산과 이진 Or 연산으로 구성됩니다. Or 작업의 결과가 IsTrue 인 경우에만 작업이 수행됩니다false.

작업은 AndAlso 단항 IsFalse 연산과 이진 And 연산으로 구성됩니다. And 작업의 결과가 IsFalse 인 경우에만 작업이 수행됩니다false.

적용 대상