Nasıl yapılır: Tür Dönüştürücü Uygulama

Bir tür dönüştürücü veri türleri arasında değerleri dönüştürmek için ve tasarım zamanında özellik yapılandırma metin değeri dönüştürme veya seçmek için değerleri aşağı açılan listesini sağlayarak size yardımcı olmak için kullanılabilir.Doğru olarak yapılandırılmışsa türü dönüştürücü kod yapılandırma özelliğini kullanarak üretebilir bir InstanceDescriptor ve System.Reflection Tasarımcı seri hale getirme sisteme özellik çalışma zamanında başlatan kod üretmek için gereken bilgileri sağlayan nesneleri.

Değer çeviri türü dönüştürücüler

Tür dönüştürücüler için desteklenen veri türleri dize değeri dönüşümler veya çeviri için veya Tasarım zamanı sırasında ve çalışma zamanında kullanılabilir.Bir ana form tasarımcısında özellik tarayıcısı gibi kullanıcı metin olarak temsil edilen bir özellik değeri türü dönüştürücüleri izin ve kullanıcı tarafından girilen metnin uygun veri türünde bir değere dönüştürmek.

Çoğu yerel veri türleri (Int32, String, numaralandırma türlerinin ve diğerleri) dize değeri dönüşümleri sağlayan ve doğrulama denetimleri gerçekleştirmek varsayılan türü dönüştürücüler vardır.Varsayılan tür dönüştürücüler olan System.ComponentModel ad ve öğeler adlı TypeConverterNameConverter.Varsayılan işlevselliği amaçlarınız için yeterli olmadığında türü dönüştürücü genişletmek veya ilişkili türü dönüştürücü olmayan özel bir tür tanýmlamak, özel tür dönüştürücüsü uygulamak.

[!NOT]

A TypeConverterAttribute özniteliği bir özellik ya da bir tür dönüştürücüsü ile ilişkilendirmek için bir veri üyesi için uygulanan genellikle.Yoksa bir TypeConverterAttribute uygulanan bir tür için bu tür özellikler veya veri üyeleri için yeniden geçerli olabilir gerekmez.

Herhangi bir kullanıcı arabirimi işlevselliği uygulama türü dönüştürücü bağımsızdır.Bu yüzden aynı tür dönüştürücüsü, hem Windows Forms ve Web Forms uygulanabilir.

Bir dize bir noktaya çevirir bir basit tür dönüştürücü uygulamak için

  1. Türetildiği sınıfı tanımla TypeConverter.

  2. Geçersiz kılma CanConvertFrom hangi türünü belirten yöntemi dönüştürücü dönüştürmek.Bu yöntemi aşırı yüklüdür.

  3. Geçersiz kılma ConvertFrom uygulayan dönüştürme yöntemi.Bu yöntemi aşırı yüklüdür.

  4. Geçersiz kılma CanConvertTo hangi türünü belirten yöntemi için dönüştürücü dönüştürebilirsiniz.Bu yöntem bir string türüne dönüştürme için geçersiz kılmak gerekli değildir.Bu yöntemi aşırı yüklüdür.

  5. Geçersiz kılma ConvertTo uygulayan dönüştürme yöntemi.Bu yöntemi aşırı yüklüdür.

  6. Geçersiz kılma IsValid(ITypeDescriptorContext, Object) doğrulamasını gerçekleştirme yöntemi.Bu yöntemi aşırı yüklüdür.

Aşağıdaki kod örneği, dönüştüren türü dönüştürücü uygulayan bir String yazdığınızda bir Point türü ve bir Point içine bir String.CanConvertTo Ve IsValid(ITypeDescriptorContext, Object) yöntemleri değil bu örnekte geçersiz kılındı.

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);
   }
}

Standart değerler listesini sağlamak için Properties penceresini türü dönüştürücüler

Türü dönüştürücü türünün özellikleri penceresi denetimdeki değerler listesini sağlar.Türü dönüştürücü türü için standart değerleri kümesi sağladığında, Özellikler penceresi denetiminde ilişkili türünde bir özellik için değer girişi alanı aşağı ok tıklatıldığında özellik değeri değerler listesini görüntüleyen görüntüler.

Bu tür dönüştürücüsü ile ilişkili türünde bir özellik bir tasarım ortamı özelliği tarayıcı seçildiğinde, değer girişi alanı aralarından seçim yapabileceğiniz özellik türü için standart değerleri aşağı açılan listesini görüntüleyen bir düğme içerir.

Özellik tarayıcısında standart değerleri aşağı açılan listesini sağlayan bir basit tür dönüştürücü uygulamak için

  1. Türetildiği sınıfı tanımla TypeConverter.

  2. Geçersiz kılma GetStandardValuesSupported yöntemi ve iade true.

  3. Geçersiz kılma GetStandardValues yöntemi ve dönüş bir StandardValuesCollection özellik türü için standart değerleri içeren.Bir özellik için standart değerleri özelliği ile aynı türde olmalıdır.

  4. Geçersiz kılma CanConvertFrom yöntemi ve iade true için bir sourceType dize türünde parametre değeri.

  5. Geçersiz kılma ConvertFrom yöntem ve özellik için uygun olan değeri temel alınarak iade value parametresi.

  6. Geçerli bir TypeConverterAttribute ile ilgili standart değerleri kümesi sağlanmaktadır türüne kendi türü dönüştürücü türünü gösterir.

Aşağıdaki örnek ile ilişkilendirilmiş türünde bir özellik için Özellikler penceresini denetlemek için standart değerleri listesini sağlayan türü dönüştürücü gösterir.Örnek türü dönüştürücü tamsayı türü ile ilişkilendirilmiş geçti özelliklerini destekler.Örnek Visual Studio ile kullanmak için bir sýnýf kitaplýðý için Kodu derleyip ekleme IntStandardValuesControl bileşen için araç.Bir örneğini eklemek IntStandardValuesControl forma tasarım modu ve kaydırma için TestInt özellik denetimi seçili durumdayken Properties penceresinde.Özellik için değer girişi alanı seçildiğinde, tıklatıldığında standart değerleri aşağı açılan listesini görüntüleyen bir aşağı oku görüntülenir.Bir tamsayı değeri girerek değeri standart değerler listesine eklemek ve özellik belirtilen değere ayarlar.

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

Çalışma zamanında başlatma özelliği için kod üreten türü dönüştürücüler

.net Framework bir özellik çalışma zamanında başlatılır tasarým anýnda dinamik özellik başlatma kodu üretmek için yeteneği sağlar.

Geliştiriciler, yapıcı tabanlı başlatma kodu üreten bir türü dönüştürücü oluşturabilirsiniz.Bu tür dönüştürücüler, çalışma zamanında bir türünün özelliklerini yapılandırmak için tasarım kümesi değerlerini kullanarak dinamik olarak yapıcı kodu oluşturabilirsiniz.Türü dönüştürücü türü ve özelliği için bir kurucu değerlerini yapılandırmak için mantığı uygular.

Bir özellik başlatmak için bir kurucu yanı sıra kodu üretmek gerekiyorsa, kod bir özel uygulama tarafından dinamik olarak üretmek olanaklı CodeDomSerializer ve uygulama bir DesignerSerializerAttribute associates, sizin CodeDomSerializer türü olan bir türü için.Bu yaklaşım, genellikle yalnızca dinamik olarak denetlenen veya özelleştirilmiş kod oluşturma bileşeni başlatma için önemli olduğu senaryolarda kullanılır.Bu yaklaşım hakkında daha fazla bilgi için belgelerine bakın CodeDomSerializer.

Özel özellik Oluşturucu tabanlı Başlatıcı oluşturmak için tür dönüştürücüsü başlatılamıyor özelliğinin türünü ilişkilendirmeniz gerekir ve türü dönüştürücü dönüştürmek için bir InstanceDescriptor.

Özellik Oluşturucu tabanlı başlatma kodu üreten bir türü dönüştürücü uygulamak için

  1. Türetildiği sınıfı tanımla TypeConverter.

  2. CanConvertTo yöntemini geçersiz kılın.destinationType Parametre eşittir InstanceDescriptor yazın, iade true.

  3. ConvertTo yöntemini geçersiz kılın.destinationType Parametre eşittir InstanceDescriptor yazın, oluşturmak ve dönüş bir InstanceDescriptor yapıcı ve kodunu üretmek için Oluşturucu bağımsız değişkenleri temsil eden.Oluşturmak için bir InstanceDescriptor uygun yapıcı ve parametreleri temsil eden, elde bir ConstructorInfo dan Type başlatılıyor çağırarak özelliğinin GetConstructorveya GetConstructors uygun yöntem imzası arayan yapıcı yöntemiyle.Ardından yeni bir örnek tanımlayıcısı oluşturup geçmesi ConstructorInfo yapıcı türünü temsil eden yazıda parametre nesneleri içeren bir dizi ile birlikte uyan yapıcı imza.

Aşağıdaki örnek türü dönüştürücü türünün özelliklerini özellik Oluşturucu tabanlı başlatma kodunu üreten uygulayan 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);      
}

Kod Derleniyor

  • Özel geliştirmek ne zaman TypeConverter, her yapı ile artırmak için yapı numarası olarak ayarlamanız önerilir.Bu eski, önbelleğe alınmış sürümlerini önler, TypeConverter tasarım ortamında oluşturulan gelen.

Ayrıca bkz.

Kavramlar

Genelleşmiş Tür Dönüştürme