Porady: implementowanie konwertera typów

Typ konwertera może służyć do konwersji wartości między typami danych i ułatwiające konfiguracji właściwości w czasie projektowania dostarczając konwersji wartości tekstowej lub listy rozwijanej wartości wybierz z.Jeśli został prawidłowo skonfigurowany, konwertera typu można utworzyć przy użyciu kodu konfiguracji właściwości InstanceDescriptor i System.Reflection obiekty, aby zapewnić system projektanta serializacji informacji niezbędnych do wyprodukowania kod, który inicjuje właściwości w czasie wykonywania.

Typ konwertery do tłumaczenia wartość

Konwertery typu może służyć do konwersji wartości ciągu lub tłumaczenie do lub z obsługiwane typy danych w czasie projektowania i w czasie wykonywania.W hosta takie jak przeglądarki własności w projektancie formularzy dzięki nim typ wartości właściwości reprezentowany jako tekst do użytkownika i ich przekonwertować tekst wprowadzany przez użytkownika na wartość odpowiedni typ danych.

Najbardziej macierzysty typy danych (Int32, String, wyliczeń i innych) ma domyślny typ konwertery, które zapewniają konwersji wartości ciągu i sprawdzania poprawności.Domyślny typ konwertery są w System.ComponentModel obszaru nazw i są o nazwie TypeConverterNameConverter.Można rozszerzyć konwertera typu, gdy funkcja domyślna nie jest odpowiedni dla własnych potrzeb lub zaimplementować konwerter niestandardowego typu podczas definiowania typ niestandardowy, który nie ma skojarzonego typu wymiennego konwertera.

[!UWAGA]

A TypeConverterAttribute atrybut jest ogólnie stosowane do właściwości lub członka danych, aby skojarzyć ją z konwertera typu.Jeśli TypeConverterAttribute jest stosowany do typu, to nie należy ponownie zastosować do właściwości lub danych członków tego typu.

Wykonania konwertera typu jest niezależny od żadnych funkcji interfejsu użytkownika.Stąd konwertera ten sam typ mogą być stosowane zarówno w Windows Forms, jak i w formularzach sieci Web.

Aby zaimplementować konwertera typu prostego, który można przetłumaczyć ciągu do punktu

  1. Zdefiniowanie klasy, która wynika z TypeConverter.

  2. Zastąpić CanConvertFrom metodę, która określa, jaki typ konwertera można przekonwertować.Ta metoda jest przeciążona.

  3. Zastąpić ConvertFrom metodę, która implementuje konwersji.Ta metoda jest przeciążona.

  4. Zastąpić CanConvertTo metodę, która określa, jaki typ konwertera można przekonwertować.Nie jest konieczne zastąpienie tej metody do konwersji na typ string.Ta metoda jest przeciążona.

  5. Zastąpić ConvertTo metodę, która implementuje konwersji.Ta metoda jest przeciążona.

  6. Zastąpić IsValid(ITypeDescriptorContext, Object) metodę, która sprawdza poprawność.Ta metoda jest przeciążona.

Poniższy przykład kodu implementuje konwertera typu, który konwertuje String należy wpisać do Point typu i Point do String.CanConvertTo i IsValid(ITypeDescriptorContext, Object) metody nie są zastępowane w tym przykładzie.

Option Explicit 
Option Strict

Imports System
Imports System.ComponentModel
Imports System.Globalization
Imports System.Drawing

Public Class PointConverter
   Inherits TypeConverter
   
   ' Overrides the CanConvertFrom method of TypeConverter.
   ' The ITypeDescriptorContext interface provides the context for the
   ' conversion. Typically, this interface is used at design time to 
   ' provide information about the design-time container.
   Public Overrides Overloads Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean
      If sourceType Is GetType(String) Then
         Return True
      End If
      Return MyBase.CanConvertFrom(context, sourceType)
   End Function
   
   ' Overrides the ConvertFrom method of TypeConverter.
   Public Overrides Overloads Function ConvertFrom(context As ITypeDescriptorContext, culture As CultureInfo, value As Object) As Object
      If TypeOf value Is String Then
         Dim v As String() = CStr(value).Split(New Char() {","c})
         Return New Point(Integer.Parse(v(0)), Integer.Parse(v(1)))
      End If
      Return MyBase.ConvertFrom(context, culture, value)
   End Function
   
   ' Overrides the ConvertTo method of TypeConverter.
   Public Overrides Overloads Function ConvertTo(context As ITypeDescriptorContext, culture As CultureInfo, value As Object, destinationType As Type) As Object
      If destinationType Is GetType(String) Then
         Return CType(value, Point).X & "," & CType(value, Point).Y
      End If
      Return MyBase.ConvertTo(context, culture, value, destinationType)
   End Function
End Class
using System;
using System.ComponentModel;
using System.Globalization;
using System.Drawing;

public class PointConverter : TypeConverter {
   // Overrides the CanConvertFrom method of TypeConverter.
   // The ITypeDescriptorContext interface provides the context for the
   // conversion. Typically, this interface is used at design time to 
   // provide information about the design-time container.
   public override bool CanConvertFrom(ITypeDescriptorContext context, 
      Type sourceType) {
      
      if (sourceType == typeof(string)) {
         return true;
      }
      return base.CanConvertFrom(context, sourceType);
   }
   // Overrides the ConvertFrom method of TypeConverter.
   public override object ConvertFrom(ITypeDescriptorContext context, 
      CultureInfo culture, object value) {
      if (value is string) {
         string[] v = ((string)value).Split(new char[] {','});
         return new Point(int.Parse(v[0]), int.Parse(v[1]));
      }
      return base.ConvertFrom(context, culture, value);
   }
   // Overrides the ConvertTo method of TypeConverter.
   public override object ConvertTo(ITypeDescriptorContext context, 
      CultureInfo culture, object value, Type destinationType) {  
      if (destinationType == typeof(string)) {
         return ((Point)value).X + "," + ((Point)value).Y;
      }
      return base.ConvertTo(context, culture, value, destinationType);
   }
}

Typ konwertery, które zawierają listę standardowych wartości w oknie właściwości

Konwerter typu może przewidywać listę wartości typu formantu okna właściwości.Gdy konwertera typu dostarcza zestaw standardowych wartości dla typu, pole wpis wartości właściwości skojarzonego typu formantu okna właściwości wyświetla strzałkę w dół, w którym wyświetlana jest lista wartości, aby ustawić wartość właściwości, aby po kliknięciu.

Zaznaczenie właściwości typu, który skojarzony jest ten typ konwertera w przeglądarce właściwości środowiska czasu projektowania, wartość pola Zapis będzie zawierać przycisk, który wyświetla listę standardowych wartości dla typu właściwości, które można wybrać z rozwijanej.

Aby zaimplementować konwertera typu prostego, który zapewnia listy rozwijanej standardowe wartości w przeglądarce właściwości

  1. Zdefiniowanie klasy, która wynika z TypeConverter.

  2. Zastąpić GetStandardValuesSupported metody i return true.

  3. Zastąpić GetStandardValues metody i powrotu StandardValuesCollection zawierających standardowych wartości dla typu właściwości.Standardowe wartości dla właściwości musi być tego samego typu jak samą właściwość.

  4. Zastąpić CanConvertFrom metody i powrotu true do sourceType wartość parametru typu ciąg.

  5. Zastąpić ConvertFrom metody i zwrotu, na podstawie odpowiednich wartości dla właściwości value parametru.

  6. Stosuje się TypeConverterAttribute , wskazuje typ konwertera programu typu typ, który podaje zestaw standardowych wartości dla.

W poniższym przykładzie zademonstrowano konwertera typu, który zawiera listę standardowych wartości do formantu okno właściwości dla właściwości typu, z którą jest skojarzony.Przykład konwertera typu obsługuje właściwości typu integer, z którym został skojarzony.Aby użyć przykładowego programu Visual Studio, należy skompilować kod, aby biblioteka klas i dodać IntStandardValuesControl składnik do Przybornik.Dodaj wystąpienia IntStandardValuesControl do formularza w trybie projektowania i przejdź do TestInt właściwość w oknie dialogowym właściwości, gdy formant jest zaznaczony.Wybierając pole zapisu wartości dla właściwości wyświetla strzałka listy rozwijanej standardowych wartości po kliknięciu wyświetla.Wprowadzając wartość całkowitą będzie dodać wartość do listy wartości standardowych i ustawić właściwość określona wartość.

using System;
using System.ComponentModel;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;

namespace StandardValuesTest
{  
    public class StandardValuesIntConverter : System.ComponentModel.TypeConverter
    {
        private ArrayList values;
        public StandardValuesIntConverter()
        {
            // Initializes the standard values list with defaults.
            values = new ArrayList(new int[] { 1, 2, 3, 4, 5 });
        }

        // Indicates this converter provides a list of standard values.
        public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context)
        {
            return true;
        }

        // Returns a StandardValuesCollection of standard value objects.
        public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context)
        {        
            // Passes the local integer array.
            StandardValuesCollection svc = 
                new StandardValuesCollection(values);       
            return svc;
        }

        // Returns true for a sourceType of string to indicate that 
        // conversions from string to integer are supported. (The 
        // GetStandardValues method requires a string to native type 
        // conversion because the items in the drop-down list are 
        // translated to string.)
        public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType)
        {
            if( sourceType == typeof(string) )
                return true;
            else 
                return base.CanConvertFrom(context, sourceType);
        }

        // If the type of the value to convert is string, parses the string 
        // and returns the integer to set the value of the property to. 
        // This example first extends the integer array that supplies the 
        // standard values collection if the user-entered value is not 
        // already in the array.
        public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if( value.GetType() == typeof(string) )
            {
                // Parses the string to get the integer to set to the property.
                int newVal = int.Parse((string)value);
            
                // Tests whether new integer is already in the list.
                if( !values.Contains(newVal) )
                {
                    // If the integer is not in list, adds it in order.
                    values.Add(newVal);
                    values.Sort();
                }                                
                // Returns the integer value to assign to the property.
                return newVal;
            }
            else
                return base.ConvertFrom(context, culture, value);
        }
    }

    // Provides a test control with an integer property associated with 
    // the StandardValuesIntConverter type converter.
    public class IntStandardValuesControl : System.Windows.Forms.UserControl
    {
        [TypeConverter(typeof(StandardValuesIntConverter))]
        public int TestInt
        {
            get
            {
                return this.integer_field;
            }
            set
            {
                if(value.GetType() == typeof(int))
                    this.integer_field = value;
            }
        }
        private int integer_field = 0;
      
        public IntStandardValuesControl()
        {
            this.BackColor = Color.White;
            this.Size = new Size(472, 80);
        }

        // OnPaint override displays instructions for the example.
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            if(this.DesignMode)
            {
                e.Graphics.DrawString("TypeConverter.GetStandardValues Example Control", new Font(FontFamily.GenericMonospace, 10), new SolidBrush(Color.Blue), 5, 5);
                e.Graphics.DrawString("The type converter for the TestInt property of this", new Font(FontFamily.GenericMonospace, 10), new SolidBrush(Color.Black), 5, 20);
                e.Graphics.DrawString("component provides a list of standard values to the", new Font(FontFamily.GenericMonospace, 10), new SolidBrush(Color.Black), 5, 30);
                e.Graphics.DrawString("Properties window. Setting a value through a property", new Font(FontFamily.GenericMonospace, 10), new SolidBrush(Color.Black), 5, 40);
                e.Graphics.DrawString("grid adds it to the list of standard values.", new Font(FontFamily.GenericMonospace, 10), new SolidBrush(Color.Black), 5, 50);             
            }
            else
            {
                e.Graphics.DrawString("TypeConverter.GetStandardValues Example Control", new Font(FontFamily.GenericMonospace, 10), new SolidBrush(Color.Blue), 5, 5);         
                e.Graphics.DrawString("This control was intended for use in design mode.", new Font(FontFamily.GenericMonospace, 10), new SolidBrush(Color.Black), 5, 20);       
            }
        }
    }
}
Imports System
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Collections
Imports System.Drawing
Imports System.Windows.Forms

Namespace StandardValuesTest

    Public Class StandardValuesIntConverter
        Inherits System.ComponentModel.TypeConverter

        Private values As ArrayList

        Public Sub New()
            ' Initializes the standard values list with defaults.
            values = New ArrayList(New Integer() {1, 2, 3, 4, 5})
        End Sub 'New

        ' Indicates this type converter provides a list of standard values.
        Public Overloads Overrides Function GetStandardValuesSupported(ByVal context As System.ComponentModel.ITypeDescriptorContext) As Boolean
            Return True
        End Function 'GetStandardValuesSupported

        ' Returns a StandardValuesCollection of standard value objects.
        Public Overloads Overrides Function GetStandardValues(ByVal context As System.ComponentModel.ITypeDescriptorContext) As System.ComponentModel.TypeConverter.StandardValuesCollection
            ' Passes the local integer array.
            Dim svc As New StandardValuesCollection(values)
            Return svc
        End Function 'GetStandardValues

        ' Returns true for a sourceType of string to indicate that 
        ' conversions from string to integer are supported. (The 
        ' GetStandardValues method requires a string to native type 
        ' conversion because the items in the drop-down list are 
        ' translated to string.)
        Public Overloads Overrides Function CanConvertFrom(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal sourceType As System.Type) As Boolean
            If sourceType Is GetType(String) Then
                Return True
            Else
                Return MyBase.CanConvertFrom(context, sourceType)
            End If
        End Function 'CanConvertFrom

        ' If the type of the value to convert is string, parses the string 
        ' and returns the integer to set the value of the property to. 
        ' This example first extends the integer array that supplies the 
        ' standard values collection if the user-entered value is not 
        ' already in the array.
        Public Overloads Overrides Function ConvertFrom(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal culture As System.Globalization.CultureInfo, ByVal value As Object) As Object
            If value.GetType() Is GetType(String) Then
                ' Parses the string to get the integer to set to the property.
                Dim newVal As Integer = Integer.Parse(CStr(value))

                ' Tests whether new integer is already in the list.
                If Not values.Contains(newVal) Then
                    ' If the integer is not in list, adds it in order.
                    values.Add(newVal)
                    values.Sort()
                End If
                ' Returns the integer value to assign to the property.
                Return newVal
            Else
                Return MyBase.ConvertFrom(context, culture, value)
            End If
        End Function 'ConvertFrom
    End Class 'StandardValuesIntConverter

    ' Provides a test control with an integer property associated with the 
    ' StandardValuesIntConverter type converter.
    Public Class IntStandardValuesControl
        Inherits System.Windows.Forms.UserControl

        <TypeConverter(GetType(StandardValuesIntConverter))> _
        Public Property TestInt() As Integer
            Get
                Return Me.integer_field
            End Get
            Set(ByVal Value As Integer)
                If Value.GetType() Is GetType(Integer) Then
                    Me.integer_field = Value
                End If
            End Set
        End Property
        Private integer_field As Integer = 0

        Public Sub New()
            Me.BackColor = Color.White
            Me.Size = New Size(472, 80)
        End Sub 'New

        ' OnPaint override displays instructions for the example.
        Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
            If Me.DesignMode Then
                e.Graphics.DrawString("TypeConverter.GetStandardValues Example Control", New Font(FontFamily.GenericMonospace, 10), New SolidBrush(Color.Blue), 5, 5)
                e.Graphics.DrawString("The type converter for the TestInt property of this", New Font(FontFamily.GenericMonospace, 10), New SolidBrush(Color.Black), 5, 20)
                e.Graphics.DrawString("component provides a list of standard values to the", New Font(FontFamily.GenericMonospace, 10), New SolidBrush(Color.Black), 5, 30)
                e.Graphics.DrawString("Properties window. Setting a value through a property", New Font(FontFamily.GenericMonospace, 10), New SolidBrush(Color.Black), 5, 40)
                e.Graphics.DrawString("grid adds it to the list of standard values.", New Font(FontFamily.GenericMonospace, 10), New SolidBrush(Color.Black), 5, 50)
            Else
                e.Graphics.DrawString("TypeConverter.GetStandardValues Example Control", New Font(FontFamily.GenericMonospace, 10), New SolidBrush(Color.Blue), 5, 5)
                e.Graphics.DrawString("This control was intended for use in design mode.", New Font(FontFamily.GenericMonospace, 10), New SolidBrush(Color.Black), 5, 20)
            End If
        End Sub 'OnPaint
    End Class 'IntStandardValuesControl
End Namespace 'StandardValuesTest

Konwertery typu generujących kod dla właściwości inicjowania w czasie wykonywania

.NET Framework zapewnia możliwość generowania kodu inicjowania właściwości dynamicznych w czasie projektowania, który zostanie zainicjowany właściwości w czasie wykonywania.

Deweloperzy mogą tworzyć converter typu, która produkuje kod inicjujący oparte konstruktora.Konwerterów typu może wygenerować kod konstruktora dynamicznie za pomocą wartości ustawione w czasie projektowania, aby skonfigurować właściwości typu w czasie wykonywania.Typ konwertera implementuje logiki do konfigurowania typu i wartości Konstruktora właściwości.

Jeśli trzeba wydrukować kod oprócz konstruktora zainicjować właściwość, jest możliwość dynamicznego generowania kodu, implementując niestandardową CodeDomSerializer i stosowania DesignerSerializerAttribute który kojarzy your CodeDomSerializer dla typu z typem.To podejście jest zazwyczaj używany tylko w scenariuszach, w których ważna jest generowanie kodu dynamicznie kontrolowane lub dostosowanych do inicjowania składnika.Aby uzyskać więcej informacji dotyczących tego podejścia, zobacz dokumentację dla CodeDomSerializer.

Aby zbudować inicjator oparte Konstruktora właściwości niestandardowych, należy skojarzyć konwertera typu z typem właściwości zainicjować i konwertera typu musi być możliwa konwersja na InstanceDescriptor.

Aby zaimplementować konwertera typu, która wywołuje kod inicjujący Konstruktora właściwości

  1. Zdefiniowanie klasy, która wynika z TypeConverter.

  2. Zastąpić CanConvertTo metody.Jeśli destinationType jest równe parametr InstanceDescriptor typu, zwrotu true.

  3. Zastąpić ConvertTo metody.Jeśli destinationType parametru jest równa InstanceDescriptor typu, skonstruować i zwraca InstanceDescriptor reprezentującym konstruktora i argumentów konstruktora do generowania kodu.Aby utworzyć InstanceDescriptor reprezentującym odpowiednie konstruktora i parametry, uzyskania ConstructorInfo z Type właściwości są inicjowanie przez wywołanie GetConstructorlub GetConstructors metoda podpisem odpowiednią metodę konstruktora oczekuje się.Następnie utwórz nowy deskryptor instancji i przekazać ConstructorInfo dla typu, który reprezentuje typ Konstruktor ma być używany, wraz z tablicą obiektów parametr pasujące podpis konstruktora.

Poniższy przykład implementuje konwertera typu, który może wygenerować kod inicjowania Konstruktora właściwości dla właściwości typu Point.

public class PointConverter : TypeConverter 
{
   public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) 
   {
      if (destinationType == typeof(InstanceDescriptor)) 
         return true;
      return base.CanConvertTo(context, destinationType);
   }

public override object ConvertTo(ITypeDescriptorContext context, 
CultureInfo culture, object value, Type destinationType) 
{
      // Insert other ConvertTo operations here.
      //
      if (destinationType == typeof(InstanceDescriptor) && 
value is Point) 
   {
         Point pt = (Point)value;

      ConstructorInfo ctor = typeof(Point).GetConstructor(
new Type[] {typeof(int), typeof(int)});
      if (ctor != null) 
      {
         return new InstanceDescriptor(ctor, new object[] {pt.X, pt.Y});
}
}
   return base.ConvertTo(context, culture, value, destinationType);      
}

Kompilowanie kodu

  • Podczas rozwijania niestandardowe TypeConverter, zaleca się, że aby ustawić numer kompilacji do zwiększania z każdej kompilacji.Zapobiega to wersjach starszych, buforowane na TypeConverter z tworzonych w środowisku projektowym.

Zobacz też

Koncepcje

Konwersja uogólnionych typów