1

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

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

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

我已经为它编写了一个自定义类型和类型转换器(并使用 TypeDescriptor 属性注册了它),但它没有被第 3 方代码使用,它在调用时失败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))); 
}
4

1 回答 1

4

你检查 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));

在那之后你的样品应该起作用。

于 2013-02-21T17:11:57.673 回答