我正在使用一些第三方代码,它使用TypeConverters将“对象”转换为指定为通用参数的类型。TypeDescriptor.GetConverter(typeof(string))无法转换为我的自定义类型
第三方代码获取字符串类型转换器,并希望通过该类型转换器执行所有转换。
var typeConverter = TypeDescriptor.GetConverter(typeof(string));
我写了一个自定义类型和类型转换器为它(并与TypeDescriptor属性注册的话),但它没有得到使用的第三方代码,从而未能在调用typeConverter.CanConvertTo(MyCustomType)
直到今天,我只会在摘要中遇到TypeConverters,我已经看到他们提到但从未构建或使用过。
有没有人知道我在做什么错在这里?
我 - 削减 - 代码
using System;
using System.ComponentModel;
namespace IoNoddy
{
[TypeConverter(typeof(TypeConverterForMyCustomType))]
public class MyCustomType
{
public Guid Guid { get; private set; }
public MyCustomType(Guid guid)
{
Guid = guid;
}
public static MyCustomType Parse(string value)
{
return new MyCustomType(Guid.Parse(value));
}
}
public class TypeConverterForMyCustomType
: TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return ((sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType));
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
string strValue;
if ((strValue = value as string) != null)
try
{
return MyCustomType.Parse(strValue);
}
catch (FormatException ex)
{
throw new FormatException(string.Format("ConvertInvalidPrimitive: Could not convert {0} to MyCustomType", value), ex);
}
return base.ConvertFrom(context, culture, value);
}
}
}
static void Main(string[] args)
{
// Analogous to what 3rd party code is doing:
var typeConverter = TypeDescriptor.GetConverter(typeof(string));
// writes "Am I convertible? false"
Console.WriteLine("Am I convertible? {0}", typeConverter.CanConvertTo(typeof(MyCustomType)));
}
http://msdn.microsoft.com/en-us/library/ayybcxe5.aspx好的地方开始阅读希望它有帮助 – MethodMan 2013-02-21 15:50:08
可能你shuld注册你的转换器? – gabba 2013-02-21 15:51:23
@gabba:谨慎地阐述?还是我应该坐在这里用stoopid棍子殴打自己? – 2013-02-21 16:03:56