DynamicObject.TryConvert(ConvertBinder, Object) Metodo
Definizione
Fornisce l'implementazione per le operazioni di conversione dei tipi.Provides implementation for type conversion operations. Le classi derivate dalla classe DynamicObject possono eseguire l'override di questo metodo per specificare il comportamento dinamico per operazioni che eseguono la conversione di un oggetto da un tipo a un altro.Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations that convert an object from one type to another.
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
Parametri
- binder
- ConvertBinder
Fornisce informazioni sull'operazione di conversione.Provides information about the conversion operation. La proprietà binder.Type
specifica il tipo in cui deve essere convertito l'oggetto.The binder.Type
property provides the type to which the object must be converted. Ad esempio, per l'istruzione (String)sampleObject
in C# (CType(sampleObject, Type)
in Visual Basic), dove sampleObject
è un'istanza della classe derivata dalla classe DynamicObject, binder.Type
restituisce il tipo String.For example, for the statement (String)sampleObject
in C# (CType(sampleObject, Type)
in Visual Basic), where sampleObject
is an instance of the class derived from the DynamicObject class, binder.Type
returns the String type. La proprietà binder.Explicit
specifica informazioni sul tipo di conversione effettuato.The binder.Explicit
property provides information about the kind of conversion that occurs. Restituisce true
per la conversione esplicita e false
per la conversione implicita.It returns true
for explicit conversion and false
for implicit conversion.
- result
- Object
Tipo di risultato dell'operazione di conversione dei tipi.The result of the type conversion operation.
Restituisce
true
se l'operazione riesce; in caso contrario, false
.true
if the operation is successful; otherwise, false
. Se questo metodo restituisce false
, il comportamento viene determinato dal gestore di associazione di runtime del linguaggio.If this method returns false
, the run-time binder of the language determines the behavior. Nella maggior parte dei casi viene generata un'eccezione di runtime specifica del linguaggio.(In most cases, a language-specific run-time exception is thrown.)
Esempio
Si supponga di avere bisogno di una struttura di dati per archiviare rappresentazioni testuali e numeriche dei numeri e di voler definire le conversioni di questa struttura di dati in stringhe e numeri interi.Assume that you need a data structure to store textual and numeric representations of numbers, and you want to define conversions of this data structure to strings and integers.
Nell'esempio di codice riportato di seguito viene illustrata la DynamicNumber
classe, derivata dalla DynamicObject classe.The following code example demonstrates the DynamicNumber
class, which is derived from the DynamicObject class. DynamicNumber
esegue l'override del TryConvert metodo per abilitare la conversione del tipo.DynamicNumber
overrides the TryConvert method to enable type conversion. Esegue inoltre l'override TrySetMember dei TryGetMember metodi e per consentire l'accesso agli elementi di dati.It also overrides the TrySetMember and TryGetMember methods to enable access to the data elements.
In questo esempio è supportata solo la conversione in stringhe e numeri interi.In this example, only conversion to strings and integers is supported. Se si tenta di convertire un oggetto in un altro tipo, viene generata un'eccezione in fase di esecuzione.If you try to convert an object to any other type, a run-time exception is thrown.
// 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
Commenti
Le classi derivate dalla DynamicObject classe possono eseguire l'override di questo metodo per specificare la modalità di esecuzione di una conversione di tipi per un oggetto dinamico.Classes derived from the DynamicObject class can override this method to specify how a type conversion should be performed for a dynamic object. Quando il metodo non viene sottoposto a override, il gestore di associazione della fase di esecuzione del linguaggio determina il comportamento.When the method is not overridden, the run-time binder of the language determines the behavior. Nella maggior parte dei casi viene generata un'eccezione di runtime specifica del linguaggio.(In most cases, a language-specific run-time exception is thrown.)
In C#, se questo metodo viene sottoposto a override, viene richiamato automaticamente quando si dispone di una conversione esplicita o implicita, come illustrato nell'esempio di codice riportato di seguito.In C#, if this method is overridden, it is automatically invoked when you have an explicit or implicit conversion, as shown in the code example below.
In Visual Basic, è supportata solo la conversione esplicita.In Visual Basic, only explicit conversion is supported. Se si esegue l'override di questo metodo, lo si chiama usando le CTypeDynamic CTypeDynamic funzioni o.If you override this method, you call it by using the CTypeDynamic or CTypeDynamic functions.
// 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))