كيفية: تنفيذ محول نوع

يمكن استخدام محوّل نوع لتحويل قيم بين أنواع بيانات، و لمساعدة تكوين الخاصية أثناء وقت التصميم بواسطة توفير تحويل القيمة إلى نص أو إسقاط-لأسفل قائمة قيم لتحديد من. تكوين بشكل صحيح، ينتج محوّل نوع خاصية تعليمات برمجية التكوين باستخدام InstanceDescriptorو System.Reflectionالكائنات إلى توفير المعلومات الضرورية للنظام المصمم لإنشاء تسلسل إلى إنتاج رمز تهيئة خاصية عند وقت التشغيل.

نوع محوّلات لترجمة القيمة

نوع محوّلات يمكن استخدامها لتحويل سلسلة إلى القيمة أو الترجمة أو من أنواع بيانات المعتمدة في وقت التصميم ووقت التشغيل. في مضيف مثل مستعرض خصائص في مصمم نماذج، اكتب محوّلات تسمح لالقيمة خاصية لكي يتم تمثيلها كنص للمستخدم، ويمكن أن تحول نص مستخدم إدخالها إلى القيمة من نوع بيانات الصحيح.

أنواع بيانات الأصلية على الأكثر ( Int32، String، أنواع التعداد، و الآخرين) يكون الافتراضي نوع المحولات التي توفر عمليات تحويل سلسلة إلى القيمة و إجراء اختبارات التحقق من صحة. الافتراضي المحوّلات نوع قيد System.ComponentModelمساحة الاسم والمسمى من TypeConverterNameConverter. يمكنك توسيع محوّل نوع عند الوظيفة الافتراضية هو غير كافية لأغراض أو تنفيذ مخصص اكتب محوّل عندما تقوم بتعريف نوع مخصص الذي لا يحتوي محوّل نوع مقترن.

ملاحظة

TypeConverterAttributeهو تطبيق السمة بشكل عام إلى خاصية أو عضو بيانات عليك إقرانه مع نوع محول. إذا كان TypeConverterAttributeهو المطبق على نوع، لم يكن لديك إلى إعادة تطبيق لأعضاء الخصائص أو بيانات من هذا النوع.

تنفيذ محوّل نوع هو مستقلة عن أية وظائف واجهة مستخدم. وبالتالي نفس نوع محوّل يمكن تطبيقها في كل من Windows Forms وفي "نماذج ويب".

لتنفيذ محوّل نوع بسيط يمكن ترجمة سلسلة إلى نقاط

  1. تعريف فئة مشتقة من TypeConverter.

  2. يمنع CanConvertFromأسلوب التي تحدد نوع المحول التي يمكن تحويل من. هذا الأسلوب مُحمّل بوظيفة أخرى.

  3. يمنع ConvertFromأسلوب الذي يطبق تحويل. هذا الأسلوب مُحمّل بوظيفة أخرى.

  4. يمنع CanConvertToأسلوب التي تحدد نوع المحول تحويل إلى. ليس من الضروري ليمنع هذا أسلوب للتحويل إلى نوع سلسلة. هذا الأسلوب مُحمّل بوظيفة أخرى.

  5. يمنع ConvertToأسلوب الذي يطبق تحويل. هذا الأسلوب مُحمّل بوظيفة أخرى.

  6. يمنع IsValidالطريقة التي يقوم بالتحقق من الصحة. هذا الأسلوب مُحمّل بوظيفة أخرى.

مثال التعليمة البرمجية التالية بتنفيذ محوّل نوع يحول Stringكتابة في Pointالنوع Pointإلى String. CanConvertToو IsValidلا يتم تجاوز الأساليب في هذا المثال.

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

اكتب محوّلات التي تقوم بتوفير قائمة قيم القياسية نافذة الخصائص

يمكن لمحول نوع توفير قائمة من قيم لنوع في عنصر تحكم نافذة خصائص. عندما يوفر محوّل نوع التعيين من قيم القياسية لنوع، حقل إدخال قيمة لخاصية من النوع المقترن في نافذة خصائص عنصر تحكم عرض سهم لأسفل يعرض قائمة قيم إلى بتعيين قيمة خاصية إلى عند النقر فوقه.

عند خاصية النوع th هو نوع محوّل هو المقترنة هو محددة في مستعرض خصائص بيئة وقت التصميم، حقل إدخال القيمة سوف يحتوي على زر هذا dهوplays lهوt قائمة منسدلة قيم القياسية لنوع الخاصية التي تقوم بمحددها من.

إلى تنفيذ محوّل نوع بسيط يوفر قائمة قائمة منسدلة بقيم القياسية في مستعرض خصائص

  1. تعريف فئة مشتقة من TypeConverter.

  2. يمنع GetStandardValuesSupportedأسلوب و بإرجاع true.

  3. يمنع GetStandardValuesالأسلوب وإرجاع TypeConverter.StandardValuesCollectionالتي تحتوي على قيم القياسية للخاصية نوع. يجب أن تكون قيم خاصية قياسية من نفس نوع كخاصية نفسه.

  4. يمنع CanConvertFromالطريقة وإرجاع true sourceTypeالقيمة معلمة نوع السلسلة.

  5. يمنع ConvertFromأسلوب و إرجاع الالقيمة المناسبة للخاصية استناداً valueمعلمة.

  6. يطبق TypeConverterAttributeالذي يشير إلى نوع محوّل النوع الخاص بك إلى النوع التي توفر التعيين من قياسي قيم for.

يوضح المثال التالي محوّل نوع الذي يوفر lهوt مقياس قيم لعنصر تحكم نافذة خصائص خاصية من النوع هو المقترنة. يعتمد محوّل نوع المثال خصائص عدد صحيح النوع الذي به تم إقرانها. باستخدام المثال في ‏‫Visual Studio .NET، ترجمة تعليمات برمجية إلى مكتبة فئة، و إضافة IntStandardValuesControlمكوّن من مربع الأدوات. إضافة مثيل IntStandardValuesControlإلى نموذج في الوضع التصميم، ثم قم بالتمرير إلى TestIntخاصية في الإطار "خصائص" مع عنصر التحكم هو المحدد. تحديد حقل إدخال القيمة خاصية يعرض يقوم بعرض قائمة منسدلة بالقيم القياسية عند النقر فوق سهم لأسفل. قم بإدخال قيمة عددية صحيحة سيضيف القيمة إلى قائمة قيم القياسية، و التعيين خاصية إلى القيمة المحددة.

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

نوع المحوّلات التي تقوم بإنشاء تعليمات برمجية تهيئة خاصية عند وقت التشغيل

يوفر إطار عمل.NET القدرة إلى توليد تعليمات برمجية لليهيّئ ديناميكي الخاصية أثناء وقت التصميم التي يتم يهيّئ خاصية أثناء وقت التشغيل.

يمكن للمطورين بنية محوّل نوع الذي ينتج عنه تهيئة المستندة إلى الدالة الإنشائية تعليمات برمجية. يمكن توليد هذه المحولات النوع الدالة الإنشائية تعليمات برمجية ديناميكياً باستخدام قيم تعيين وقت التصميم من أجل تكوين خصائص نوع وقت التشغيل. نوع المحول بتطبيق منطق لتكوين النوع و قيم على الدالة الإنشائية للخاصية.

إذا كنت بحاجة لإنشاء تعليمات برمجية بالإضافة إلى على الدالة الإنشائية يهيّئ خاصية، فمن الممكن حيويا توليد تعليمات برمجية? بواسطة تطبيق مخصص CodeDomSerializerوتطبيق DesignerSerializerAttributeالذي يقوم بربط الخاص بك CodeDomSerializerلنوع مع النوع. This approach هو typically used فقط for scenarios في which dynamically controlled أو مخصص إنشاء التعليمة البرمجية for مكوّن تهيئة هو important. For المزيد معلومات تشغيل this approach, see the documentation for CodeDomSerializer.

إلى بنية a مخصص الدالة الإنشائية-based خاصية initializer, you must associate a نوع محوّل مع the نوع of the خاصية إلى يهيّئ, و the نوع محوّل must be able إلى تحويل إلى an InstanceDescriptor.

إلى implement a نوع محوّل that produces الدالة الإنشائية-based خاصية تهيئة تعليمات برمجية

  1. تعريف فئة مشتقة من TypeConverter.

  2. تجاوز الأسلوب CanConvertTo. If the destinationType معلمة يساوي InstanceDescriptor نوع, return true.

  3. تجاوز الأسلوب ConvertTo. If the destinationType معلمة يساوي the InstanceDescriptor نوع, construct و return an InstanceDescriptor that represents the الدالة الإنشائية و الدالة الإنشائية الوسيطات إلى توليد تعليمات برمجية for. إلى إنشاء an InstanceDescriptor that represents the appropriate الدالة الإنشائية و معلمات, obtain a ConstructorInfo من the Type of the خاصية you are initializing بواسطة calling the GetConstructorأو GetConstructors أسلوب مع the appropriate أسلوب توقيع of the الدالة الإنشائية you are seeking. Then إنشاء a جديد مثيل descriptor و pass the ConstructorInfo for the نوع that represents the الدالة الإنشائية نوع إلى استخدم, along مع an مصفوفه من معلمة الكائنات that مطابقة the الدالة الإنشائية توقيع.

The following مثال implements a نوع محوّل that can توليد الدالة الإنشائية-based خاصية تهيئة تعليمات برمجية for خصائص of نوع 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);      
}

التحويل البرمجي للتعليمات البرمجية

  • When you develop your مخصص TypeConverter, it هو recommended that you التعيين the بنية رقم إلى increment مع each بنية. This prevents older, cached versions of your TypeConverter من being تاريخ الإنشاء في the تصميم بيئة.

راجع أيضًا:

المبادئ

تحويل نوع معمم