TypeConverter 类

定义

提供一种将值的类型转换为其他类型以及访问标准值和子属性的统一方法。Provides a unified way of converting types of values to other types, as well as for accessing standard values and subproperties.

public ref class TypeConverter
public class TypeConverter
[System.Runtime.InteropServices.ComVisible(true)]
public class TypeConverter
type TypeConverter = class
Public Class TypeConverter
继承
TypeConverter
派生
属性

示例

下面的代码示例演示如何创建类型转换器的实例并将其绑定到类。The following code example shows how to create an instance of a type converter and bind it to a class. 实现转换器 MyClassConverter类必须继承自 TypeConverter 类。The class implementing the converter, MyClassConverter, must inherit from the TypeConverter class.

public:
   [TypeConverter(Sample::MyClassConverter::typeid)]
   ref class MyClass
   {
      // Insert code here.
   };
[TypeConverter(typeof(MyClassConverter))]
 public class MyClass {
    // Insert code here.
}
<TypeConverter(GetType(MyClassConverter))> _
Public Class Class1
    ' Insert code here.
End Class

如果具有具有枚举的属性,请在设置属性之前查看枚举值是否有效。When you have a property that has an enumeration, check to see whether an enumeration value is valid before setting the property. 下一个代码示例需要已声明 MyPropertyEnum 的枚举。The next code example requires that an enumeration called MyPropertyEnum has been declared.

public:
   property MyPropertyEnum MyProperty 
   {
      void set( MyPropertyEnum value )
      {
         // Checks to see if the value passed is valid.
         if ( !TypeDescriptor::GetConverter( MyPropertyEnum::typeid )->IsValid( value ) )
         {
            throw gcnew ArgumentException;
         }
         // The value is valid. Insert code to set the property.
      }
   }
public MyPropertyEnum MyProperty {
    set {
       // Checks to see if the value passed is valid.
       if (!TypeDescriptor.GetConverter(typeof(MyPropertyEnum)).IsValid(value)) {
          throw new ArgumentException();
       }
       // The value is valid. Insert code to set the property.
    }
 }

Public WriteOnly Property MyProperty() As MyPropertyEnum
    Set
        ' Checks to see if the value passed is valid.
        If Not TypeDescriptor.GetConverter(GetType(MyPropertyEnum)).IsValid(value) Then
            Throw New ArgumentException()
        End If
        ' The value is valid. Insert code to set the property.
    End Set 
End Property

另一种常见的类型转换器用法是将对象转换为字符串。Another common type converter usage is to convert an object to a string. 下面的代码示例输出变量 c中存储的 Color 的名称。The following code example prints out the name of the Color stored in the variable c.

Color c = Color::Red;
Console::WriteLine( TypeDescriptor::GetConverter( c )->ConvertToString( c ) );
Color c = Color.Red;
    Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c));
Dim c As Color = Color.Red
Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c))

还可以使用类型转换器从其名称转换值,如下面的代码示例中所示。You can also use a type converter to convert a value from its name, as shown in the next code example.

Color c =  (Color)(TypeDescriptor::GetConverter( Color::typeid )->ConvertFromString( "Red" ));
Color c = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString("Red");
Dim c As Color = CType(TypeDescriptor.GetConverter(GetType(Color)).ConvertFromString("Red"), Color)

在下面的代码示例中,可以使用类型转换器输出对象支持的标准值集。In the following code example, you can use a type converter to print out the set of standard values that the object supports.

for each ( Color c in TypeDescriptor::GetConverter( Color::typeid )->GetStandardValues() )
{
   Console::WriteLine( TypeDescriptor::GetConverter( c )->ConvertToString( c ) );
}
foreach(Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues()) {
    Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c));
 }
Dim c As Color
For Each c In  TypeDescriptor.GetConverter(GetType(Color)).GetStandardValues()
    Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c))
Next c

注解

最常见的转换器类型是在文本表示形式之间进行转换的转换器。The most common type of converter is one that converts to and from a text representation. 类的类型转换器绑定到带有 TypeConverterAttribute的类。The type converter for a class is bound to the class with a TypeConverterAttribute. 除非重写此属性,否则,从此类继承的所有类都将使用与基类相同的类型转换器。Unless this attribute is overridden, all classes that inherit from this class use the same type converter as the base class.

备注

对于常规类型系统目的,不要直接访问类型转换器。For general type system purposes, do not access a type converter directly. 相反,请使用 TypeDescriptor访问适当的转换器。Instead, access the appropriate converter by using TypeDescriptor. 有关详细信息,请参阅提供的代码示例。For more information, see the code examples provided.

但是,在使用 XAML 时,XAML 处理器会直接搜索 TypeConverterAttribute,而不是通过 TypeDescriptorHowever, when using XAML, a XAML processor searches for the TypeConverterAttribute directly, instead of going through TypeDescriptor. 对于需要从代码中 TypeDescriptor 实例的情况,或在 WPF 资源中创建共享实例的情况,可以在不引用 TypeDescriptor 或其他反射和类型系统支持的情况下直接构造它。For cases where you do want a TypeDescriptor instance from code, or where you create a shared instance in WPF resources, it is acceptable to construct it directly without referencing TypeDescriptor or other reflection and type system support.

通常会将从 TypeConverter 中派生的类作为 XAML 处理器如何从标记(本质上是字符串)转换特性或初始化文本值的一部分进行引用,并为运行时表示形式生成对象。Classes derived from TypeConverter are often referenced as part of how a XAML processor converts an attribute or initialization text value from markup (which is inherently a string) and generates an object for a run-time representation. 要支持 XAML 的类型转换行为的自定义类型作者通常实现 TypeConverter 类,该类支持其自己的唯一 ConvertFrom 行为。Custom type authors that intend to support a type conversion behavior for XAML typically implement a TypeConverter class that supports their own unique ConvertFrom behavior from a string. 此行为可实现从提供的字符串到 XAML 特性值的类型转换,并为 XAML 处理器提供从字符串创建对象所需的支持,以便可以在分析的对象图中生成该对象。This behavior enables type conversion from the string provided as a XAML attribute value and provides a XAML processor with the support needed to create an object from the string, so that the object can be produced in a parsed object graph. 自定义类型或自定义类型的成员通过将 TypeConverterAttribute 应用于定义来指示,特性引用自定义 TypeConverter 实现。Custom types or members of custom types are indicated by applying TypeConverterAttribute to the definitions, with the attribute referencing the custom TypeConverter implementation. 有关详细信息,请参阅XAML 的类型转换器概述For more information, see Type Converters for XAML Overview.

继承者说明

TypeConverter 继承以实现您自己的转换要求。Inherit from TypeConverter to implement your own conversion requirements. 从此类继承时,可以重写以下方法:When you inherit from this class, you can override the following methods: -若要支持自定义类型转换,请重写 CanConvertFrom(ITypeDescriptorContext, Type)CanConvertTo(ITypeDescriptorContext, Type)ConvertFrom(ITypeDescriptorContext, CultureInfo, Object)ConvertTo(ITypeDescriptorContext, CultureInfo, Object, Type) 方法。- To support custom type conversion, override the CanConvertFrom(ITypeDescriptorContext, Type), CanConvertTo(ITypeDescriptorContext, Type), ConvertFrom(ITypeDescriptorContext, CultureInfo, Object), and ConvertTo(ITypeDescriptorContext, CultureInfo, Object, Type) methods.

-若要转换必须重新创建对象以更改其值的类型,请重写 CreateInstance(ITypeDescriptorContext, IDictionary)GetCreateInstanceSupported(ITypeDescriptorContext) 方法。- To convert types that must re-create the object to change its value, override the CreateInstance(ITypeDescriptorContext, IDictionary) and GetCreateInstanceSupported(ITypeDescriptorContext) methods.

-若要转换支持属性的类型,请重写 GetProperties(ITypeDescriptorContext, Object, Attribute[])GetPropertiesSupported(ITypeDescriptorContext) 方法。- To convert types that support properties, override the GetProperties(ITypeDescriptorContext, Object, Attribute[]) and GetPropertiesSupported(ITypeDescriptorContext) methods. 如果要转换的类不具有属性,并且您需要实现属性,则可以使用 TypeConverter.SimplePropertyDescriptor 类作为实现属性说明符的基础。If the class you are converting does not have properties, and you need to implement properties, you can use the TypeConverter.SimplePropertyDescriptor class as a base for implementing the property descriptors. TypeConverter.SimplePropertyDescriptor继承时,必须重写 GetValue(Object)SetValue(Object, Object) 方法。When you inherit from TypeConverter.SimplePropertyDescriptor, you must override the GetValue(Object) and SetValue(Object, Object) methods.

-若要转换支持标准值的类型,请重写 GetStandardValues(ITypeDescriptorContext)GetStandardValuesExclusive(ITypeDescriptorContext)GetStandardValuesSupported(ITypeDescriptorContext)IsValid(ITypeDescriptorContext, Object) 方法。- To convert types that support standard values, override the GetStandardValues(ITypeDescriptorContext), GetStandardValuesExclusive(ITypeDescriptorContext), GetStandardValuesSupported(ITypeDescriptorContext) and IsValid(ITypeDescriptorContext, Object) methods.


派生类型可能标记为 internalprivate,但可以使用 TypeDescriptor 类创建类型的实例。Your derived type might be marked as internal or private, but an instance of your type can be created with the TypeDescriptor class. 如果调用方是受信任的,请勿编写不安全代码。Do not write insecure code by assuming the caller is trusted. 假定调用方可以在部分信任环境中创建类型的实例。Assume instead that callers might create instances of your type in partial trust.

有关常规(非 XAML)用途的类型转换器的详细信息,请参阅[如何:实现类型转换器](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/ayybcxe5(v=vs.120))或[通用类型转换](https://msdn.microsoft.com/library/49253ae6-7657-4810-82ab-1176a6feeada)。For more information about type converters for general (non-XAML) purposes, see [How to: Implement a Type Converter](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/ayybcxe5(v=vs.120)) or [Generalized Type Conversion](https://msdn.microsoft.com/library/49253ae6-7657-4810-82ab-1176a6feeada).

构造函数

TypeConverter()

初始化 TypeConverter 类的新实例。Initializes a new instance of the TypeConverter class.

方法

CanConvertFrom(ITypeDescriptorContext, Type)

返回该转换器是否可以使用指定上下文将给定类型的对象转换为此转换器的类型。Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.

CanConvertFrom(Type)

返回该转换器是否可以将给定类型的对象转换为此转换器的类型。Returns whether this converter can convert an object of the given type to the type of this converter.

CanConvertTo(ITypeDescriptorContext, Type)

返回此转换器能否使用指定上下文将对象转换为指定类型。Returns whether this converter can convert the object to the specified type, using the specified context.

CanConvertTo(Type)

返回此转换器是否可将该对象转换为指定的类型。Returns whether this converter can convert the object to the specified type.

ConvertFrom(ITypeDescriptorContext, CultureInfo, Object)

使用指定的上下文和区域性信息将给定对象转换为此转换器的类型。Converts the given object to the type of this converter, using the specified context and culture information.

ConvertFrom(Object)

将给定值转换为此转换器的类型。Converts the given value to the type of this converter.

ConvertFromInvariantString(ITypeDescriptorContext, String)

使用不变区域性和指定上下文将给定字符串转换为此转换器的类型。Converts the given string to the type of this converter, using the invariant culture and the specified context.

ConvertFromInvariantString(String)

使用不变区域性将给定字符串转换为此转换器的类型。Converts the given string to the type of this converter, using the invariant culture.

ConvertFromString(ITypeDescriptorContext, CultureInfo, String)

使用指定的上下文和区域性信息将给定的文本转换为对象。Converts the given text to an object, using the specified context and culture information.

ConvertFromString(ITypeDescriptorContext, String)

使用指定的上下文将给定的文本转换为对象。Converts the given text to an object, using the specified context.

ConvertFromString(String)

将指定文本转换为对象。Converts the specified text to an object.

ConvertTo(ITypeDescriptorContext, CultureInfo, Object, Type)

使用指定的上下文和区域性信息将给定值对象转换为指定的类型。Converts the given value object to the specified type, using the specified context and culture information.

ConvertTo(Object, Type)

使用参数将给定的值对象转换为指定的类型。Converts the given value object to the specified type, using the arguments.

ConvertToInvariantString(ITypeDescriptorContext, Object)

使用指定的上下文将指定的值转换为区域性不变的字符串表示形式。Converts the specified value to a culture-invariant string representation, using the specified context.

ConvertToInvariantString(Object)

将指定值转换为区域性不变的字符串表示形式。Converts the specified value to a culture-invariant string representation.

ConvertToString(ITypeDescriptorContext, CultureInfo, Object)

使用指定的上下文和区域性信息将给定的值转换为字符串表示形式。Converts the given value to a string representation, using the specified context and culture information.

ConvertToString(ITypeDescriptorContext, Object)

使用给定的上下文将给定的值转换为字符串表示形式。Converts the given value to a string representation, using the given context.

ConvertToString(Object)

将指定值转换为字符串表示形式。Converts the specified value to a string representation.

CreateInstance(IDictionary)

在给定 Object 的一组属性值的情况下重新创建该对象。Re-creates an Object given a set of property values for the object.

CreateInstance(ITypeDescriptorContext, IDictionary)

给定该对象的一组属性值,使用指定上下文创建与此 TypeConverter 相关联的类型的实例。Creates an instance of the type that this TypeConverter is associated with, using the specified context, given a set of property values for the object.

Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetConvertFromException(Object)

返回当转换无法执行时所引发的异常。Returns an exception to throw when a conversion cannot be performed.

GetConvertToException(Object, Type)

返回当转换无法执行时所引发的异常。Returns an exception to throw when a conversion cannot be performed.

GetCreateInstanceSupported()

返回更改此对象的值是否求调用 CreateInstance(IDictionary) 方法来创建新值。Returns whether changing a value on this object requires a call to the CreateInstance(IDictionary) method to create a new value.

GetCreateInstanceSupported(ITypeDescriptorContext)

返回一个结果,即更改此对象上的某个值是否需要调用 CreateInstance(IDictionary) 以使用指定的上下文创建新值。Returns whether changing a value on this object requires a call to CreateInstance(IDictionary) to create a new value, using the specified context.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetProperties(ITypeDescriptorContext, Object)

使用指定的上下文返回值参数指定的数组类型的属性的集合。Returns a collection of properties for the type of array specified by the value parameter, using the specified context.

GetProperties(ITypeDescriptorContext, Object, Attribute[])

使用指定的上下文和特性返回由该值参数指定的数组类型的属性集合。Returns a collection of properties for the type of array specified by the value parameter, using the specified context and attributes.

GetProperties(Object)

返回由值参数指定的数组类型的属性集合。Returns a collection of properties for the type of array specified by the value parameter.

GetPropertiesSupported()

返回此对象是否支持属性。Returns whether this object supports properties.

GetPropertiesSupported(ITypeDescriptorContext)

通过使用指定的上下文,返回此对象是否支持属性。Returns whether this object supports properties, using the specified context.

GetStandardValues()

从默认的上下文返回此类型转换器设计用于的数据类型的标准值集合。Returns a collection of standard values from the default context for the data type this type converter is designed for.

GetStandardValues(ITypeDescriptorContext)

当与格式上下文一起提供时,返回此类型转换器设计用于的数据类型的标准值集合。Returns a collection of standard values for the data type this type converter is designed for when provided with a format context.

GetStandardValuesExclusive()

返回从 GetStandardValues() 返回的标准值的集合是否为独占列表。Returns whether the collection of standard values returned from GetStandardValues() is an exclusive list.

GetStandardValuesExclusive(ITypeDescriptorContext)

使用指定的上下文返回从 GetStandardValues() 返回的标准值的集合是否为可能值的独占列表。Returns whether the collection of standard values returned from GetStandardValues() is an exclusive list of possible values, using the specified context.

GetStandardValuesSupported()

返回此对象是否支持可以从列表中选取的值的标准集。Returns whether this object supports a standard set of values that can be picked from a list.

GetStandardValuesSupported(ITypeDescriptorContext)

使用指定的上下文返回此对象是否支持可以从列表中选取的标准值集。Returns whether this object supports a standard set of values that can be picked from a list, using the specified context.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
IsValid(ITypeDescriptorContext, Object)

返回给定的值对象是否对此类型和对指定的上下文有效。Returns whether the given value object is valid for this type and for the specified context.

IsValid(Object)

返回给定值对象对于此类型是否有效。Returns whether the given value object is valid for this type.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
SortProperties(PropertyDescriptorCollection, String[])

对属性的集合进行排序。Sorts a collection of properties.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

适用于

另请参阅