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# の ステートメント (String)sampleObject (CType(sampleObject, Type) Visual Basic では ) sampleObject の 場合、 は クラスから DynamicObject 派生したクラスのインスタンスであり、 binder.Type は 型を String 返します。 プロパティは binder.Explicit 、発生する変換の種類に関する情報を提供します。 このプロパティは、明示的な変換の場合は true、暗黙の変換の場合は false を返します。

result
Object

型変換演算の結果。

戻り値

操作が正常に終了した場合は true。それ以外の場合は false。 このメソッドが false を返す場合、言語のランタイム バインダーによって動作が決まります (ほとんどの場合、言語固有の実行時例外がスローされます)。

数値のテキスト表現と数値表現を格納するためのデータ構造が必要であり、このデータ構造の文字列と整数への変換を定義する必要があるとします。

次のコード例では、 DynamicNumber クラスから派生した クラスを DynamicObject 示します。 DynamicNumber は、 メソッドを TryConvert オーバーライドして型変換を有効にします。 また、 メソッドと TryGetMember メソッドをTrySetMemberオーバーライドして、データ要素へのアクセスを有効にします。

この例では、文字列と整数への変換のみがサポートされています。 オブジェクトを他の型に変換しようとすると、実行時例外がスローされます。

// 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 オーバーライドして、動的オブジェクトに対して型変換を実行する方法を指定できます。 メソッドがオーバーライドされない場合、言語の実行時バインダーによって動作が決まります。 (ほとんどの場合、言語固有の実行時例外がスローされます)。

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))  

適用対象