开发者

Tracking what collections a class instance/object is a member of

Is there a way in .NET (C#) when using the debugger to know what collec开发者_JS百科tions an object is currently in.

I have a situation where class instances are moving in and out of different Lists and Arrays and am trying to track down which collections at any point in time it is currently in. i.e. when i hit a breakpoint.

The only solution I can think of is coding some kind of tracker class. Was hoping the debugger might have a way of tracing this.

Edit: I guess its kind of like the way you can expand a collection in the debugger and see the members, except I'd like to do the reverse.

Thanks.


It sounds like you would benefit from using the observer pattern, which creates a "one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically". Basically, you have an object that receives a notification whenever an item gets added to a collection.

.NET 4 has a built in implementation of this pattern. Check out Observer Design Pattern in .NET.

Interface Documentation:

  • IObserver
  • IObservable<T>

It also may be worthwhile to look at the ObservableCollection<T> class, and see if that would provide the functionality you need. It is available in .NET 3.


I don't believe there's anything like this built-in, but it would be pretty easy to create. Just add expressions to the Watch window, one per collection.

Or create a single function in your code that searches the collections and returns, say, an array of strings (collection names) - and call that function from the Watch window.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜