TypeConverter实现无法识别对象类型

时间:2019-09-22 21:19:25

标签: c# typeconverter

我为自定义类 Foo 实现了TypeConverter,我想覆盖对字符串的转换。

问题是:在我的替代方法 ConvertTo 中,测试表达式(值为Foo foo)始终失败,尽管该值的类型为Foo。

通过Locals检查变量表明 value 的类型为 object {MyNamespace.Foo} 类型。

我在做什么错?

 [TypeConverter(typeof(FooConverter))]
    public class Foo
    {
    }

public class FooConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
        if (sourceType == typeof(string)) return true;
        return base.CanConvertFrom(context, sourceType);
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
        if (destinationType == typeof(Foo)) return true;
        return base.CanConvertTo(context, destinationType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
        if (value is string valStr) {
            //custom conversion, does not matter
        }
        return base.ConvertFrom(context, culture, value);
    }

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
        if (destinationType == typeof(string)) {
            if (value is Foo fooCast) //this test always fails, why?
            {
                //custom parse, does not matter
                return parseResult;
            }
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

0 个答案:

没有答案