问题
Is it possible in .net to get all instances of concrete type created in application? I guess such information is stored in GC, but is it accessible from code?
回答1:
Check Raymond Chen's blog about why that's a bad idea(except for debugging). http://blogs.msdn.com/b/oldnewthing/archive/2010/08/12/10049155.aspx
And to implement it you'd need to walk all objects on the heap since it's unlikely that the CLR keeps track of the object by type, so it would be very slow.
回答2:
No, it's not available normally. It's possible that the debugging/profiling API lets you get at this (obviously only the as-yet-uncollected instances) but not in normal code.
回答3:
Not sure what your scenario is, but I can't see when this information would be useful. Also what would be the scope of such information, thread? app domain? assembly? For example it doesn't make any sense to say give me a list of all int objects within the app domain, does it?
If this is for a certain type that you created then you can constraint the creation of objects of that type by using some kind of a factory class. There you can keep track of all objects that are instantiated for your given type.
Hope this helps.
来源:https://stackoverflow.com/questions/4159887/net-is-it-possible-to-get-object-instances-created-earlier-by-class-type