Skip to main content
 首页 » 编程设计

c#之如何避免为我的每个类使用单独的自定义 TypeDescriptor Provider

2024年02月24日16xiaohuochai

我已经在我的项目中添加了允许用户将他们自己的自定义属性添加到对象的功能。我已经创建了我自己的自定义 TypeDescriptor、PropertyDescriptor 和 TypeDescriptorProviders 等...等等...来执行此操作。

这是我的问题。现在我已经全部正常工作,但必须为每个可以具有自定义属性的对象对象类型创建一个单独的 TypeDescriptionProvider。这是我的 TypeDescriptionProviders 的样子

//type AClass Custom Provider 
class AClassTypeProvider : TypeDescriptionProvider 
{ 
    private static TypeDescriptionProvider defaultTypeProvider = TypeDescriptor.GetProvider(typeof(AClass)); 
 
    public AClassTypeProvider (): base(defaultTypeProvider) 
    { 
 
    } 
 
    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) 
    { 
        ICustomTypeDescriptor defaultDescriptor = base.GetTypeDescriptor(objectType, instance); 
 
        //returns a custom type descriptor based on a UserPropertyHostType enum value, and the default descriptor 
        return new InfCustomTypeDescriptor(UserPropertyHostType.SiteRegion, defaultDescriptor); 
    } 
} 
 
 
//type BClass Custom Provider 
class BClassTypeProvider : TypeDescriptionProvider 
{ 
    private static TypeDescriptionProvider defaultTypeProvider =   TypeDescriptor.GetProvider(typeof(BClass)); 
 
    public BClassTypeProvider (): base(defaultTypeProvider) 
    { 
 
    } 
 
    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) 
    { 
        ICustomTypeDescriptor defaultDescriptor = base.GetTypeDescriptor(objectType, instance); 
 
        //returns a custom type descriptor based on a UserPropertyHostType enum value, and the default descriptor 
        return new InfCustomTypeDescriptor(UserPropertyHostType.Building, defaultDescriptor); 
    } 
} 

因此,我的每个自定义 TypeDescriptionProvider 通过将特定类型的默认 TypeDescriptionProvider 传递给它来调用 base(TypeDescriptionProvider parent) 基本构造函数。

GetTypeDescriptor() 方法调用 base.GetTypeDescriptor() 来获取默认描述符,然后我的自定义类型描述符使用它来添加自定义属性。

有没有办法将它们组合成一个具有相同功能但不绑定(bind)到特定类型的通用自定义 TypeDescriptionProvider?我是否可以跳过在构造函数中提供父级 TypeDescriptionProvider 但稍后在我明确知道查询的对象类型时在 GetTypeDescriptor() 方法中设置它?或者除了调用 base.GetTypeDescriptor(Type t,object ins) 方法之外,还有其他获取类型默认描述符的方法吗?

请您参考如下方法:

这个泛型类应该做你想做的事:

class CustomTypeProvider<T> : TypeDescriptionProvider 
{ 
    private static TypeDescriptionProvider defaultTypeProvider = TypeDescriptor.GetProvider(typeof(T)); 
 
    public CustomTypeProvider(): base(defaultTypeProvider) 
    { 
 
    } 
 
    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) 
    { 
        ICustomTypeDescriptor defaultDescriptor = base.GetTypeDescriptor(objectType, instance); 
 
        //returns a custom type descriptor based on a UserPropertyHostType enum value, and the default descriptor 
        return new InfCustomTypeDescriptor(UserPropertyHostType.SiteRegion, defaultDescriptor); 
    } 
}