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 是派生自 类DynamicObject的类的实例,binder.TypeString返回 类型。 属性 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 中,仅支持显式转换。 如果重写此方法,则使用 CTypeDynamicCTypeDynamic 函数调用它。

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

适用于