DynamicObject.TryConvert(ConvertBinder, Object) 메서드

정의

형식 변환 연산에 대한 구현을 제공합니다. DynamicObject 클래스에서 파생된 클래스로 이 메서드를 재정의하여 개체를 한 형식에서 다른 형식으로 변환하는 연산의 동적 동작을 지정할 수 있습니다.

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

매개 변수

binder
ConvertBinder

변환 연산에 대한 정보를 제공합니다. 속성은 binder.Type 개체를 변환해야 하는 형식을 제공합니다. 예를 들어 C#(CType(sampleObject, Type)Visual Basic의 경우)의 문 (String)sampleObject 에 대해 는 sampleObject 클래스 binder.Type 에서 DynamicObject 파생된 클래스의 instance 형식을 String 반환합니다. 속성이 binder.Explicit 발생 하는 변환의 종류에 대 한 정보를 제공 합니다. 명시적 변환의 경우 true를 반환하고, 암시적 변환의 경우 false를 반환합니다.

result
Object

형식 변환 연산의 결과입니다.

반환

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

예제

숫자의 텍스트 및 숫자 표현을 저장하기 위해 데이터 구조가 필요하고 이 데이터 구조를 문자열 및 정수로 변환하는 것을 정의하려고 한다고 가정합니다.

다음 코드 예제에서는 DynamicNumber 클래스에서 파생 된 클래스를 보여 줍니다 DynamicObject . DynamicNumber 형식 변환을 사용하도록 메서드를 재정의 TryConvert 합니다. 또한 및 TryGetMember 메서드를 재정의 TrySetMember 하여 데이터 요소에 액세스할 수 있도록 합니다.

이 예제에서는 문자열 및 정수로의 변환만 지원됩니다. 개체를 다른 형식으로 변환하려고 하면 런타임 예외가 throw됩니다.

// The class derived from DynamicObject.
public class DynamicNumber : DynamicObject
{
    // The inner dictionary.
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();

    // Getting a property.
    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        return dictionary.TryGetValue(binder.Name, out result);
    }

    // Setting a property.
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;
        return true;
    }

    // Converting an object to a specified type.
    public override bool TryConvert(
        ConvertBinder binder, out object result)
    {
        // Converting to string.
        if (binder.Type == typeof(String))
        {
            result = dictionary["Textual"];
            return true;
        }

        // Converting to integer.
        if (binder.Type == typeof(int))
        {
            result = dictionary["Numeric"];
            return true;
        }

        // In case of any other type, the binder
        // attempts to perform the conversion itself.
        // In most cases, a run-time exception is thrown.
        return base.TryConvert(binder, out result);
    }
}

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;

        // Implicit conversion to integer.
        int testImplicit = number;

        // Explicit conversion to string.
        string testExplicit = (String)number;

        Console.WriteLine(testImplicit);
        Console.WriteLine(testExplicit);

        // The following statement produces a run-time exception
        // because the conversion to double is not implemented.
        // double test = number;
    }
}

// This example has the following output:

// 1
// One
' 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

    Public Overrides Function TryConvert(ByVal binder As System.Dynamic.ConvertBinder, ByRef result As Object) As Boolean
        ' Converting to string. 
        If binder.Type = GetType(String) Then
            result = dictionary("Textual")
            Return True
        End If

        ' Converting to integer.
        If binder.Type = GetType(Integer) Then
            result = dictionary("Numeric")
            Return True
        End If
        ' In case of any other type, the binder 
        ' attempts to perform the conversion itself.
        ' In most cases, a run-time exception is thrown.
        Return MyBase.TryConvert(binder, result)
    End Function
End Class

Sub Main()
    ' 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


    ' Explicit conversion to string.
    Dim testString = CTypeDynamic(Of String)(number)
    Console.WriteLine(testString)

    ' Explicit conversion to integer.
    Dim testInteger = CTypeDynamic(number, GetType(Integer))
    Console.WriteLine(testInteger)

    ' The following statement produces a run-time exception
    ' because the conversion to double is not implemented.
    ' Dim testDouble = CTypeDynamic(Of Double)(number)

End Sub
' This example has the following output:

' One
' 1

설명

클래스에서 파생된 클래스는 이 메서드를 재정의 DynamicObject 하여 동적 개체에 대해 형식 변환을 수행하는 방법을 지정할 수 있습니다. 메서드를 재정의하지 않으면 언어의 런타임 바인더가 동작을 결정합니다. 대부분의 경우 언어별 런타임 예외가 throw됩니다.

C#에서 이 메서드가 재정의되면 아래 코드 예제와 같이 명시적 또는 암시적 변환이 있을 때 자동으로 호출됩니다.

Visual Basic에서는 명시적 변환만 지원됩니다. 이 메서드를 재정의하는 경우 또는 CTypeDynamic 함수를 CTypeDynamic 사용하여 호출합니다.

// Explicit conversion.  
String sampleExplicit = (String)sampleObject;  
// Implicit conversion.  
String sampleImplicit = sampleObject;  
// Explicit conversion - first variant.  
Dim testExplicit1 = CTypeDynamic(Of String)(sampleObject)  
// Explicit conversion - second variant.  
Dim testExplicit2 = CTypeDynamic(sampleObject, GetType(String))  

적용 대상