gpt4 book ai didi

c# - 创建使用 CollectionEditor 的自定义 IList 类

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:16 25 4
gpt4 key购买 nike

我有一个用户控件,它有一个属性,该属性是自定义对象类型的列表。当我通过从 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(或类似的东西)在设计器中编辑它,我需要知道何时进行这些设计器更改,以便我可以更新控件的外观。

最佳答案

您可以按照框架集合的方式实现您的自定义集合。不要看太多。

像往常一样实现非泛型 IList,但将实现的方法设为私有(private)。然后为每个实现的方法添加另一个公共(public)方法,但这次这些公共(public)方法将接受您想要的自定义类型。这些方法将通过类型转换从已实现的私有(private)方法中调用。

这是框架集合遵循的方式。看看 UIElementCollection类(class)。您将看到完全相同的实现。

IList.Add 方法的示例:假设自定义类称为 TextElement

private int IList.Add(object value)
{
return Add((TextElement)value);
}

public int Add(TextElement element)
{
[Your custom logic here]
}

编辑:您不能只使用私有(private)方法隐式实现接口(interface)。你必须明确地这样做。例如,您需要执行 private int IList.Add 而不是 private int Add,并且 private void ICollection.CopyTo 而不是 private void CopyTo 所有这些都可以工作。

关于c# - 创建使用 CollectionEditor 的自定义 IList 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21978363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com