c# - 将类型描述符添加到所有 List<T> 以实现属性网格扩展的通用实现?

标签 c# winforms generics propertygrid typedescriptor

我定义了一个自定义 ExpandableObjectConverter对于集合:

internal class ExpandableCollectionConverter : ExpandableObjectConverter
{
    public override PropertyDescriptorCollection GetProperties(
        ITypeDescriptorContext context, object value, Attribute[] attributes)
    {
        //implementation that returns a list of property descriptors,
        //one for each item in "value"
    }
}

还有一个名为ExpandableObjectManager的代理类,本质上是这样做的:

TypeDescriptor.AddAttributes(type,
  new TypeConverterAttribute(typeof(ExpandableCollectionConverter)));

使用这个方法:

public static class ExpandableObjectManager
{
    public static void AddTypeDescriptor(Type tItem)
    {
        //eventually calls TypeDescriptor.AddAttributes
    }
}

是否有可能以所有通用的方式添加类型描述符 List<T>将在属性网格中扩展?例如,给定一个简单的 Employee类:

class Employee
{
    public string Name { get; set; }
    public string Title { get; set; }
    public DateTime DateOfBirth { get; set; }
}

我可以做到这一点(它有效,但仅适用于 List<Employee> ):

ExpandableObjectManager.AddTypeDescriptor(typeof(List<Employee>));

我想涵盖所有 T ,不只是 Employee ,而不必为每个可能的类写 1 行。我试过了 - 没用:

ExpandableObjectManager.AddTypeDescriptor(typeof(List<>));

TL;DR:设置为 SelectedObject 时列表的默认 View 在属性网格中:

enter image description here

预期结果:

enter image description here

无需为 List<Employee> 添加类型描述符, 而不是为所有 List<T> 提供一些通用处理程序.

最佳答案

编辑:我添加了第三种可能性。

我认为这些都不是很好的解决方案,但有以下三种可能性:

将 TypeConverterAttribute 添加到通用类型实现的接口(interface)。这里的缺点是您可能无法准确命中目标类型,但它比选项 2 更好,因为它更专注于您想要的类型。

TypeDescriptor.AddAttributes(typeof(IList), new
    TypeConverterAttribute(typeof(ExpandableCollectionConverter)));

将 TypeConverterAttribute 添加到 object类型。缺点是这会使您的类型转换器成为项目中所有类型的类型转换器。

TypeDescriptor.AddAttributes(typeof(object), new
    TypeConverterAttribute(typeof(ExpandableCollectionConverter)));

创建您自己的继承自 List<> 的列表类型并让它在静态构造函数中注册自己

public class CustomList<T> : List<T>
{
    static CustomList()
    {
        TypeDescriptor.AddAttributes(typeof(CustomList<T>), new TypeConverterAttribute(typeof(ExpandableCollectionConverter)));
    }
}

关于c# - 将类型描述符添加到所有 List<T> 以实现属性网格扩展的通用实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27570488/

相关文章:

c# - CSV 导入(可变字段)

c# - 方法中的 new()

C# 编译器无法识别正在实现接口(interface)的类

c# - 如何检查字符串数组是否包含特定字符串?

c# - 写入 CSV 文件并导出?

c# - 我们应该缓存原始对象还是排序后的对象?

c# - azure worker roleOutput类型为Class Library的项目无法直接启动

c# - 事件触发时显示警报消息

winforms - 我们如何清除winform上的所有表单控件?

winforms - EXE 和 MSI 之间的最佳方法