Condividi tramite


Esempio di convertitore di tipi

Aggiornamento: novembre 2007

In questo esempio viene illustrato come creare un convertitore di tipi denominato AuthorConverter, cheviene utilizzato con l'oggetto Author da altri esempi di creazione di controlli. ASP.NET utilizza i convertitori di tipi in fase di esecuzione per serializzare e deserializzare gli oggetti archiviati nello stato di controllo e nello stato di visualizzazione. L'esempio AuthorConverter converte un oggetto Author in una String e una rappresentazione String in un oggetto Author. Il tipo Author è descritto in Esempio di proprietà dei controlli server.

Un convertitore di tipi viene associato a un tipo (o a una proprietà del tipo per cui viene definito il convertitore) mediante la classe TypeConverterAttribute. AuthorConverter consente al controllo Book di archiviare la proprietà Author nello stato di visualizzazione. Un tipo personalizzato può essere archiviato nello stato di visualizzazione solo se per lo stesso è stato definito un convertitore di tipi e se questo è stato associato al tipo.

La classe AuthorConverter deriva dalla classe ExpandableObjectConverter in modo che il browser della proprietà in una finestra di progettazione visiva possa fornire un'interfaccia utente di tipo espandi/comprimi per modificare le sottoproprietà del tipo Author.

Listato di codice per la classe AuthorConverter

' AuthorConverter.vb
Imports System
Imports System.ComponentModel
Imports System.ComponentModel.Design.Serialization
Imports System.Globalization
Imports System.Reflection

Namespace Samples.AspNet.VB.Controls
    Public Class AuthorConverter
        Inherits ExpandableObjectConverter

        Public Overrides Function CanConvertFrom( _
        ByVal context As ITypeDescriptorContext, _
            ByVal sourceType As Type) As Boolean
            If sourceType Is GetType(String) Then
                Return True
            End If
            Return MyBase.CanConvertFrom(context, sourceType)
        End Function

        Public Overrides Function CanConvertTo( _
        ByVal context As ITypeDescriptorContext, _
            ByVal destinationType As Type) As Boolean
            If destinationType Is GetType(String) Then
                Return True
            End If
            Return MyBase.CanConvertTo(context, destinationType)
        End Function

        Public Overrides Function ConvertFrom( _
        ByVal context As ITypeDescriptorContext, _
        ByVal culture As CultureInfo, ByVal value As Object) As Object
            If value Is Nothing Then
                Return New Author()
            End If

            If (TypeOf value Is String) Then
                Dim s As String = CStr(value)
                If s.Length = 0 Then
                    Return New Author()
                End If

                Dim parts() As String = s.Split(" ".ToCharArray)

                ' Determine if name is stored as first and last, 
                ' first, middle, and last,
                ' or is in error.
                If (parts.Length < 2) Or (parts.Length > 3) Then
                    Throw New ArgumentException( _
                        "Name must have 2 or 3 parts.", "value")
                End If

                If parts.Length = 2 Then
                    Return New Author(parts(0), parts(1))
                End If

                If parts.Length = 3 Then
                    Return New Author(parts(0), parts(1), parts(2))
                End If
            End If
            Return MyBase.ConvertFrom(context, culture, value)
        End Function

        Public Overrides Function ConvertTo( _
            ByVal context As ITypeDescriptorContext, _
        ByVal culture As CultureInfo, ByVal value As Object, _
        ByVal destinationType As Type) As Object
            If value IsNot Nothing Then
                If Not (TypeOf value Is Author) Then
                    Throw New ArgumentException("Invalid Author", _
                        "value")
                End If
            End If

            If destinationType Is GetType(String) Then
                If value Is Nothing Then
                    Return String.Empty
                End If

                Dim auth As Author = CType(value, Author)

                If auth.MiddleName <> String.Empty Then
                    Return String.Format("{0} {1} {2}", _
                    auth.FirstName, _
                    auth.MiddleName, _
                    auth.LastName)
                Else
                    Return String.Format("{0} {1}", _
                         auth.FirstName, _
                        auth.LastName)
                End If
            End If

            Return MyBase.ConvertTo(context, culture, value, _
                destinationType)
        End Function

    End Class
End Namespace
// AuthorConverter.cs
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;

namespace Samples.AspNet.CS.Controls
{
    public class AuthorConverter : ExpandableObjectConverter
    {
        public override bool CanConvertFrom(
            ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(
            ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return true;
            }
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext 
            context, CultureInfo culture, object value)
        {
            if (value == null)
            {
                return new Author();
            }

            if (value is string)
            {
                string s = (string)value;
                if (s.Length == 0)
                {
                    return new Author();
                }

                string[] parts = s.Split(' ');

                        // Determine if name is stored as first and 
                        // last; first, middle, and last;
                        // or is in error.
                if ((parts.Length < 2) || (parts.Length > 3))
                {
                    throw new ArgumentException(
                        "Name must have 2 or 3 parts.", "value");
                }

                if (parts.Length == 2)
                {
                    return new Author(parts[0], parts[1]);
                }

                if (parts.Length == 3)
                {
                    return new Author(parts[0], parts[1], parts[2]);
                }
            }

            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(
            ITypeDescriptorContext context,
            CultureInfo culture, object value, Type destinationType)
        {
            if (value != null)
            {
                if (!(value is Author))
                {
                    throw new ArgumentException(
                        "Invalid Author", "value");
                }
            }

            if (destinationType == typeof(string))
            {
                if (value == null)
                {
                    return String.Empty;
                }

                Author auth = (Author)value;

                if (auth.MiddleName != String.Empty)
                {
                    return String.Format("{0} {1} {2}",
                        auth.FirstName,
                        auth.MiddleName,
                        auth.LastName);
                }
                else
                {
                    return String.Format("{0} {1}",
                         auth.FirstName,
                        auth.LastName);
                }
            }

            return base.ConvertTo(context, culture, value, 
                destinationType);
        }
    }
}

Illustrazione del codice

L'implementazione della classe AuthorConverter illustra le attività da eseguire per convertire un'istanza di Author in e da una stringa:

  • Eseguire l'override del metodo CanConvertFrom, che determina se da un tipo specifico è possibile creare un'istanza Author. Viene restituito true se il tipo passato è di tipo String.

  • Eseguire l'override del metodo CanConvertTo, che determina se un'istanza Author può essere convertita in un tipo. Viene restituito true se il tipo passato è di tipo String.

  • Eseguire l'override del metodo ConvertFrom, che restituisce una stringa che contiene le proprietà FirstName, MiddleName e LastName dell'istanza Author.

  • Eseguire l'override del metodo ConvertTo, che analizza una stringa che contiene le proprietà FirstName, MiddleName e LastName concatenate di un'istanza Author. Restituisce una nuova istanza della classe Author con i dati provenienti dalla stringa concatenata.

Creazione e utilizzo dell'esempio

Compilare la classe AuthorConverter con il controllo Book e le relative classi, descritte in Esempio di proprietà dei controlli server.

Per informazioni sulla compilazione e l'utilizzo degli esempi di controllo personalizzati, vedere Generazione degli esempi dei controlli server personalizzati.

Vedere anche

Concetti

Tipi di valore nel sistema di tipi comuni

Altre risorse

Sviluppo di controlli server ASP.NET personalizzati