Skip to main content
 首页 » 编程设计

c#之TypeDescriptor.GetConverter(typeof(string)) 无法转换为我的自定义类型

2024年02月20日12开发

我正在使用一些第三方代码,这些代码使用 TypeConverter 将对象“转换”为指定为通用参数的类型。

第 3 方代码获取字符串类型转换器,并期望通过它进行所有转换,例如

var typeConverter = TypeDescriptor.GetConverter(typeof(string)); 

我已经为它编写了一个自定义类型和类型转换器(并使用 TypeDescriptor 属性注册了它)但是它没有被第 3 方代码使用,它在调用 typeConverter.CanConvertTo(MyCustomType) 时失败)

直到今天,我只是抽象地遇到过 TypeConverter,我看到过对它们的提及,但从未构建或使用过。

有人知道我在这里做错了什么吗?

我的-砍-代码

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)));  
} 

请您参考如下方法:

你检查 CanConvertTo 所以添加到你的转换器:

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

一些地方:

    public static void Register<T, TC>() where TC : TypeConverter 
    { 
        Attribute[] attr = new Attribute[1]; 
        TypeConverterAttribute vConv = new TypeConverterAttribute(typeof(TC)); 
        attr[0] = vConv; 
        TypeDescriptor.AddAttributes(typeof(T), attr); 
    }    

和主要的:

Register<string, TypeConverterForMyCustomType>();             
var typeConverter = TypeDescriptor.GetConverter(typeof(string)); 

你的样本应该在那之后工作。