C#如何实现类型转换器 [英] c# how to implement type converter
问题描述
我正在努力用C#实现一个简单的Type转换器.我遵循了本指南 https://msdn.microsoft.com/en-us/library/ayybcxe5.aspx
I am struggling to implement a simple Type converter in C#. I followed this guide https://msdn.microsoft.com/en-us/library/ayybcxe5.aspx
这是我的课程:
public class TestClass: TypeConverter
{
public string Property1{ get; set; }
public int Property2 { get; set; }
public TestClass(string p1, int p2)
{
Property1= p1;
Property2 = p2;
}
public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
if (value is string) {
return new TestClass ("", Int32.Parse(value.ToString()));
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string)) {
return "___"
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
我执行以下 TestClass(",, Int32.Parse(value.ToString()));
,因为现在我只对" 1231->这样的情况感兴趣;新的TestClass(",1231)
I do the following TestClass ("", Int32.Parse(value.ToString()));
as for now I am only interested in such case as "1231" -> new TestClass("", 1231)
下面是给我一个例外的代码;
And here goes the code that gives me an exception;
TypeConverter converter=TypeDescriptor.GetConverter( typeof(TestClass));
Object lalala = converter.ConvertFromString("234");
此代码引发 NotSupportedException
,但我不知道为什么
This code throws NotSupportedException
but I don't get why
推荐答案
您必须将此转换器附加到具有 TypeConverter
属性的类. TypeDescriptor.GetConverter
获取该类的附加转换器.
You have to attach this converter to a class with the TypeConverter
attribute.
TypeDescriptor.GetConverter
Get the attached converter of the class.
您最好拆分课程:
[TypeConverter(typeof (TestClassConverter))]
public class TestClass
{
public string Property1 { get; set; }
public int Property2 { get; set; }
public TestClass(string p1, int p2)
{
Property1 = p1;
Property2 = p2;
}
}
[TypeConverter(typeof (TestClassConverter))]
public class TestClassConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
if (value is string)
{
return new TestClass("", Int32.Parse(value.ToString()));
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string)) { return "___"; }
return base.ConvertTo(context, culture, value, destinationType);
}
}
这篇关于C#如何实现类型转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!