1

我有一个用 a 装饰的基类,TypeDescriptionProviderAttribute它指向ICustomTypeDescriptor.

有一个派生类装饰有一个TypeConverterAttribute做自定义类型转换。

BaseClassTypeDescriptor通过ICustomTypeDescriptor.GetConverter调用静态TypeDescriptor.GetConverter方法来实现。该方法有两个参数:有问题的类型(我有一个引用)和一个指示是否允许调用自定义行为的标志。这必须设置为true防止无限循环。

代码的精简版本如下所示:

[TypeDescriptionProvider(typeof(BaseClassTypeDescriptionProvider))]
public class BaseClass
{
    public class BaseClassTypeDescriptionProvider : TypeDescriptionProvider
    {
        public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType_, object instance_)
        {
            return new BaseClassTypeDescriptor(objectType_);
        }
    }

    public class BaseClassTypeDescriptor : ICustomTypeDescriptor 
    {
         private Type _type;

         public BaseClassTypeDescriptor(Type type_)
         {
             _type = type_;
         }

         TypeConverter ICustomTypeDescriptor.GetConverter()
         {
             return TypeDescriptor.GetConverter(_type, true);
         }
    }
}

[TypeConverter(typeof(MyTypeConverter))]
public class DerivedClass : BaseClass
{
}

问题是这个标志似乎不仅绕过BaseClassTypeDescriptor,而且似乎阻止 .NET 识别TypeConverterAttribute派生类上的 。

TypeConverterAttribute我已经通过重新实现对我的实现内部的检查来解决这个问题MyCustomTypeConverter.GetConverter,如下所示:

TypeConverter ICustomTypeDescriptor.GetConverter()
{
    object[] typeConverterAttributeArray = _type.GetCustomAttributes(typeof(TypeConverterAttribute), true);
    if (typeConverterAttributeArray.Length == 1)
    {
        TypeConverterAttribute a = (TypeConverterAttribute)typeConverterAttributeArray[0];
        Type converterType = MyTypeLoader.GetType(a.ConverterTypeName);
        return (TypeConverter)Activator.CreateInstance(converterType);
    }
    else
    {
        return TypeDescriptor.GetConverter(_type, true);
    }
}

这远非理想的解决方案。关于如何将责任委托给它所属的地方有什么建议吗?

4

1 回答 1

0

在您的示例中,重载 ofTypeDescriptor.GetConverter(object component, bool noCustomTypeDesc)似乎返回TypeDescriptorType类型,因为它需要一个实例。

我试过你的例子

return TypeDescriptor.GetConverter(Activator.CreateInstance(_type), true);

bool并获得了该值应该防止的无限循环。

我不知道为什么会这样,也不知道这是否以某种方式记录在案,但我敢打赌他们根本不希望TypeDescriptionProvider打电话TypeDescriptor.GetConverter()

于 2015-05-07T18:43:06.493 回答