.NET组件编程(5) TypeConverterAttribute,类型转换2011-09-26 博客园 mapserver上一篇文章是03-08写的,距离今天已经有十多天了没有写了,主要是最近太忙了,而且在工作上遇到 了一些难点,所以没有时间放在blog上,实在是对不住大家。今天的这篇文章,我主要是带来PropertyAttribute里的TypeConverterAttribute的讲解,首先在这里 讲讲TypeConverterAttribute的作用是什么:当Component的某个Property被设置时,如Size="60,70", 解析器会通过类型转化器,把这个字符串自动转换为属性声明的类型。.net的框架中已经声明了很多的类 型转化器,下面的代码中有列举到。有点类似于operator。同时在Asp.net服务器控件的编写中TypeConverterAttribute也将会非常有用,服务器控件的Property 只能以string形式保存在aspx页面里,而在服务器控件的DesignTime和RunTime时必须要把string转换为 相应的类型。源代码如下:using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Globalization;
namespace ClassLibrary1 { public class Class1 : Component { private Size _size;
public Class1() { _size = new Size(); }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [TypeConverter(typeof(SizeConverter))] // —— 注1,也可以把这 句TypeConverterAttribute写在注2处。 public Size Size { get { return _size; } set { _size = value; } } }
public class SizeConverter : TypeConverter // 我们自定义的Converter 必须继承于TypeConverter基类。 { /**//// <summary> /// 是否能用string转换到Size类型。 /// </summary> /// <param name="context">上下文。</param> /// <param name="sourceType">转换源的Type。</param> /// <returns></returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } else { return false; } }