C# 将类型描述符添加到所有列表<;T>;对于属性网格扩展的通用实现?
我为集合定义了自定义C# 将类型描述符添加到所有列表<;T>;对于属性网格扩展的通用实现?,c#,winforms,generics,propertygrid,typedescriptor,C#,Winforms,Generics,Propertygrid,Typedescriptor,我为集合定义了自定义ExpandableObjectConverter: internal class ExpandableCollectionConverter : ExpandableObjectConverter { public override PropertyDescriptorCollection GetProperties( ITypeDescriptorContext context, object value, Attribute[] attribut
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
都可以在属性网格中展开?例如,给定一个简单的Employee
类:
class Employee
{
public string Name { get; set; }
public string Title { get; set; }
public DateTime DateOfBirth { get; set; }
}
我可以做到这一点(它可以工作,但只适用于List
):
TL;DR:在属性网格中设置为
SelectedObject
时列表的默认视图:
预期成果:
不必为
List
添加类型描述符,而是为所有List
编辑添加一些通用处理程序:我添加了第三种可能性
我认为这些都不是很好的解决方案,但有三种可能性:
向泛型类型实现的接口添加TypeConverterAttribute。这里的缺点是,您可能无法精确地命中目标类型,但它比选项2更好,因为它更关注您想要的类型
TypeDescriptor.AddAttributes(typeof(IList), new
TypeConverterAttribute(typeof(ExpandableCollectionConverter)));
将TypeConverterAttribute添加到对象
类型。缺点是,这将使您的类型转换器成为项目中所有类型的类型转换器
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)));
}
}
公共类自定义列表:列表
{
静态自定义列表()
{
AddAttributes(typeof(CustomList),新的TypeConverterAttribute(typeof(ExpandableCollectionConverter));
}
}
谢谢您的回复。不幸的是,这两个选项对我都不起作用,因为#1一些对象已经有了一个可扩展对象转换器的良好实现,如果我设置自己的,我会破坏它。例如,枚举#2我不想创建一个自定义类来表示列表。它给程序增加了不必要的复杂性。现有程序集也无法使用它。完全可以理解。如果我找到更好的选择,我会分享。我增加了第三个选择。我首先列出它,因为它似乎是最可行的。
TypeDescriptor.AddAttributes(typeof(object), new
TypeConverterAttribute(typeof(ExpandableCollectionConverter)));
public class CustomList<T> : List<T>
{
static CustomList()
{
TypeDescriptor.AddAttributes(typeof(CustomList<T>), new TypeConverterAttribute(typeof(ExpandableCollectionConverter)));
}
}