0%

CSharp补课笔记TypeConverter

实现不同类型之间的转换, 如动态的将字符串转换为对象实例

示例

使用示例

1
2
3
4
5
6
7
8
9
10
public void TestTypeConvert()
{
TypeConverter tc = TypeDescriptor.GetConverter(typeof(ColorRGB));

ColorRGB colorRGB1 = (ColorRGB)tc.ConvertFromString("#FF8800");
ColorRGB colorRGB2 = (ColorRGB)tc.ConvertFromString("255, 136, 0");

string colorString1 = tc.ConvertToString(colorRGB1);
string colorString2 = tc.ConvertToString(colorRGB2);
}

自定义类型

1
2
3
4
5
6
7
8
9
10
11
12
//将转换器与目标类型关联
[TypeConverter(typeof(ColorRGBConverter))]
public class ColorRGB
{
public byte R; public byte G; public byte B;
public ColorRGB(byte r, byte g, byte b)
{ R = r; G = g; B = b; }
public override string ToString()
{
return string.Format("#{0:X2}{1:X2}{2:X2}", R, G, B);
}
}

定义类型转换器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

internal class ColorRGBConverter : TypeConverter
{
//定义可以从哪些类型转换
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}

public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return base.CanConvertTo(context, destinationType);
}

//实现将字符串转化为对象
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if(value is string strValue)
{
try
{
if(strValue.StartsWith("#"))
{
if (strValue.Length == 7)
return new ColorRGB(byte.Parse(strValue.Substring(1,2), NumberStyles.HexNumber),
byte.Parse(strValue.Substring(3,2), NumberStyles.HexNumber),
byte.Parse(strValue.Substring(5,2), NumberStyles.HexNumber));
}
else
{
string[] parts = strValue.Split(',');
return new ColorRGB(byte.Parse(parts[0].Trim()),
byte.Parse(parts[1].Trim()),
byte.Parse(parts[2].Trim()));
}
}
catch
{
throw new FormatException("格式不正确");
}
}
return base.ConvertFrom(context, culture, value);
}

public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if(value is ColorRGB && destinationType == typeof(string))
return value.ToString();
return base.ConvertTo(context, culture, value, destinationType);
}
}

扩展

CultureInfo主要用于特定区域的数字, 日期, 货币等格式化设置