如何为自定义类中的List <t>属性创建索引访问器?</t>

时间:2011-07-26 14:30:59

标签: c# winforms class indexing properties

以下是示例:

    /// <summary>
    /// Collection of SednaTreeViewItems used to populate the SednaTreeView.
    /// </summary>
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public List<SednaTreeViewItem> TreeNodes
    {
        get { return treeNodes; }
        set 
        {
            ultraTree.Nodes.Clear();
            treeNodes = value;
            foreach (var item in treeNodes)
            {
                UltraTreeNode node = new UltraTreeNode(item.ValueMember, item.DisplayMember);
                ultraTree.Nodes.Add(node);
            }

            if (treeNodes.Count() > 0)
                ultraTree.ActiveNode = ultraTree.Nodes[0];
        }
    }

    /// <summary>
    /// SednaTreeViewItem that is currently selected in the SednaTreeView.
    /// </summary>
    public SednaTreeViewItem SelectedItem
    {
        get 
        {
            if (ultraTree.SelectedNodes != null)
            {
                var node = ultraTree.SelectedNodes[0];
                SednaTreeViewItem item = new SednaTreeViewItem(node.Key, node.Text);
                return item;
            }
            else
                return null;                
        }

        set 
        {
            ultraTree.ActiveNode = ultraTree.Nodes[value.ValueMember];
        }
    }

我想以这种方式使用我的控件。例如,有人想在运行时设置选定的树视图节点,我想要像:

treeViewInvestors.SelectedItem = treeViewInvestor.TreeNodes[userIdKey];

其中userIdKey是幕后已经存在的唯一键。

基本上,有没有办法为我的属性创建索引“[]”访问器?

2 个答案:

答案 0 :(得分:2)

实施indexer属性,如:

public SednaTreeViewItem this[int index]//or public T this[int index]
{
   get { return ultraTree[index]; }
   set { ultraTree[index] = value; }
}

答案 1 :(得分:2)

如果公开的节点集合属性是List(已经有类型为int的索引器),并且您需要另一种类型的索引器,那么您可以将treenode集合公开为具有另一种类型的列表的子类索引器:

public class NodeList : List<Node>
{
   public TNode this[Key key] 
   {
       get { return nodes.Where(n => n.Key == key).SingleOrDefault(); }
   }
}

然后您可以通过两种索引访问

var nodeByKey = treeViewInvestor.TreeNodes[key];
var nodeByIndex = treeViewInvestor.TreeNodes[index].