共用方式為


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 會提供對象必須轉換成的型別。 例如,針對 Visual Basic) 中 C# (中的 語句(String)sampleObject,其中 sampleObject 是衍生自 DynamicObject 類別的類別實例,binder.TypeString傳回 型CType(sampleObject, Type)別。 屬性 binder.Explicit 提供所發生轉換類型的相關信息。 如果是明確轉換則會傳回 true,如果是隱含轉換則會傳回 false

result
Object

型別轉換作業的結果。

傳回

如果作業成功,則為 true,否則為 false。 如果這個方法傳回 false,語言的執行階段繫結器會決定行為。 (在大多數情況下,將會擲回特定語言的執行階段例外狀況)。

範例

假設您需要數據結構來儲存數位的文字和數值表示,而且您想要定義此數據結構的轉換至字串和整數。

下列程式代碼範例示範 DynamicNumber 衍生自 類別的 DynamicObject 類別。 DynamicNumberTryConvert 覆寫 方法來啟用類型轉換。 它也會覆寫 TrySetMemberTryGetMember 方法,以啟用對數據元素的存取。

在此範例中,只支援轉換成字串和整數。 如果您嘗試將對象轉換成任何其他類型,則會擲回運行時例外狀況。

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

適用於