开发者

Use collection properties with member object

If I have a collection, say Cells, and if referenced like so Cells[1,1] it gives me an object of that collection but the member object doesn't have a certa开发者_如何学Pythonin property that the collection object has. Is there a way to call that property from the member? Like as follows, assuming StartPosition is a property of the object class for the collection:

Cells[1,1].StartPosition

or maybe

Cells[1,1].ParentCollection.StartPosition


You can only call properties that are defined on the object you are accessing.

That is, if you want to call a method on the collection, call it on the collection, not on the content of the collection.

You could add a reference to the containing collection to each item you put in it, if you design and construct your classes that way.

Note:

Your notation is array notation, for 2 dimensional arrays. Though arrays are collections, most .NET collections are not considered to be arrays, even if they do have indexers.


You could either wrap that in a propert of the Cell or what you are returning. So you'd add this to the Cell class:

public int StartPosition { 
    get { return this.ParentCollection.StartPosition; } 
}

If you can't change the class you can add an extension method, e.g.:

public static class CellExtensions {
 public static int GetStartPosition(this Cell cell) {
   return cell.ParentCollection.StartPosition;
 }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜