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);
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(Visual Basic 中的 CType(sampleObject, Type)),其中 sampleObject 是從 DynamicObject 類別衍生出的類別實例,binder.Type 回傳 String 型態。 該 binder.Explicit 物業提供關於轉換類型資訊。 它會回傳 true 給顯式轉換和 false 隱性轉換。

result
Object

這是型別轉換操作的結果。

傳回

如果作業成功,則為 true,否則為 false。 若此方法回傳 false,該語言的執行時綁定器決定行為。 (大多數情況下會拋出語言特定的執行時例外。)

範例

假設你需要一個資料結構來儲存數字的文字和數字表示,並且你想定義這個資料結構的轉換成字串和整數。

以下程式碼範例展示了 DynamicNumber 由該 DynamicObject 類別衍生而來的類別。 DynamicNumber 覆蓋 TryConvert 該方法以啟用型別轉換。 同時也會覆寫 TrySetMember and TryGetMember 方法,以啟用對資料元素的存取。

在此範例中,僅支援轉換為字串與整數。 如果你嘗試將物件轉換成其他類型,會拋出執行時例外。

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

適用於