我有一个用户控件,该控件的属性是自定义对象类型的列表。当我通过继承List 创建自定义类时,它通常可以工作:public class CustomCol : List<CustomItem> { // ...}然后,我可以在用户控件中实现如下属性:CustomCol _items = new CustomCol();[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]public CustomCol Items{ get { return _items; }}这使得它的行为符合我的预期。我可以单击设计器中的省略号按钮,它会弹出CollectionEditor,并且正确添加项目会添加CustomItems。不幸的是,这种方法不允许我检测何时在CollectionEditor中添加,删除或修改项目。经过大量研究,我发现这是因为设计器编辑器调用IList.Add()来添加新项,并且这是不可覆盖的,因此,如果不从头实现IList的基础上实现自己的集合类,就无法拦截这些调用。所以这正是我尝试做的。我尝试的代码如下所示:public class CustomCol: System.Collections.IList{ private List<CustomItem> = new List<CustomItem>(); int System.Collections.IList.Add(Object value) { _items.Add((CustomItem)value); return _items.Count; } // All of the other IList methods are similarly implemented.}在继续之前,我已经看到一个问题。 CollectionEditor将传递通用的System.Objects,而不是我的CustomItem类。因此,我接下来尝试的是改为实现IList,如下所示:public class CustomCol: IList<CustomClass>{ private List<CustomItem> = new List<CustomItem>(); void ICollection<CustomItem>.Add(NameValueItem item) { _items.Add(item); } // All of the other IList methods are similarly implemented.}从理论上讲,这是可行的,但我根本无法让CollectionEditor在设计器中启动。我整天都在工作,在网上寻找解决方案,并尝试着了解所有工作原理。在这一点上,我头疼得很重,正在寻找任何指导。总结一下:我想创建一个用户控件,该控件的属性是一个自定义集合类,可以使用CollectionEditor(或等效的东西)在Designer中进行编辑,并且我需要知道何时对这些Designer进行了更改以便更新控件的外观。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 您可以采用框架集合的方式来实现自定义集合。别看太多照常实现非通用IList,但将实现的方法设为私有。然后为每个实现的方法添加另一个公共方法,但是这次这些公共方法将接受您想要的自定义类型。这些方法将通过类型转换从已实现的私有方法中调用。这就是框架集合遵循的方式。看一下UIElementCollection类。您将看到完全相同的实现。IList.Add方法的示例:假设自定义类称为TextElement。private int IList.Add(object value){ return Add((TextElement)value);}public int Add(TextElement element){ [Your custom logic here]}编辑:您不能只使用私有方法隐式实现接口。您必须明确地做到这一点。例如,您需要执行private int IList.Add而不是private int Add,并执行private void ICollection.CopyTo而不是private void CopyTo才能使所有这些工作。关于c# - 创建一个使用CollectionEditor的自定义IList类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21978363/ (adsbygoogle = window.adsbygoogle || []).push({});