简体   繁体   English

从特定索引处的可观察集合中检索项目

[英]Retrieve items from an observable collection at specific indexes

I am trying to retrieve items at specific index locations from an ObservableCollection. 我正在尝试从ObservableCollection检索特定索引位置的项目。 According to MSDN , there are properties Item and Items . 根据MSDN ,有属性ItemItems

private ObservableCollection<string> _strings = new ObservableCollection<string>();
string item1;
item1 _strings.Item[0];
item1 _strings.Items[0];

When I use Item , I get: 当我使用Item ,我得到:

'System.Collections.ObjectModel.ObservableCollection' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'System.Collections.ObjectModel.ObservableCollection' could be found (are you missing a using directive or an assembly reference?) 'System.Collections.ObjectModel.ObservableCollection'不包含'Item'的定义,找不到扩展方法'Item'接受类型为'System.Collections.ObjectModel.ObservableCollection'的第一个参数(您是否缺少using指令或装配参考?)

And when I use Items , I get: 当我使用Items ,我得到:

Cannot access protected member 'System.Collections.ObjectModel.Collection.Items' via a qualifier of type 'System.Collections.ObjectModel.ObservableCollection'; 无法通过类型'System.Collections.ObjectModel.ObservableCollection'的限定符访问受保护的成员'System.Collections.ObjectModel.Collection.Items'; the qualifier must be of type 'Model.MyStringCollection' (or derived from it) 限定符必须为'Model.MyStringCollection'类型(或从其派生)

I just cannot see what I am doing wrong here, right now. 我现在看不到我在做什么错。

You just call it like: 您可以这样称呼它:

private ObservableCollection<string> _strings = new ObservableCollection<string>();
...

string item1 = _strings[0];

But you need to add to the collection first! 但是您需要先添加到集合中!

When any class has an indexed property it gets labeled as and Item property. 当任何类具有索引属性时,它将被标记为和Item属性。 This allows referencing the indexer property with object[index] syntax, not object.Item[index] syntax. 这允许使用object[index]语法而不是object.Item[index]语法引用indexer属性。 This is due to the fact that the property needs a name, and is a property defined as 这是由于该属性需要一个名称,并且该属性定义为

public T this[int index]
{
    get 
    {
        //...
    }
    set        
    {
        //...
    }
}

EDIT: See this article on indexer properties for further reading 编辑:请参阅这篇有关索引器属性的文章,以进一步阅读

The right syntax is this: 正确的语法是这样的:

_strings.Item(0);

not this 不是这个

_strings.Item[0];

The call to Item() or Items() is actually a method call. Item()Items()的调用实际上是方法调用。 The indexer operator is not needed. 不需要索引器运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM