I am working on a large project, and one of my tasks is to remove possible memory leaks. In my code, I have noticed several IDisposable items not being disposed of, and have fixed that. However, that leads me to a more basic question, how do I find all classes used in my project that implement IDisposable? (Not custom-created classes but standard Library classes that have been used).
I have already found one less-than-obvious class that implements IDisposable ( DataTable implements MarshalByValueComponent, which inherits IDisposable). Right now, I am manually checking any suspected classes by using MSDN, but isn't there some way through which I can automate this process?
问题:
回答1:
Reflector can show you which classes implement IDisposable
: just locate the IDisposable
interface in Reflector, and expand the "Derived types" node
Another option, from code, is to scan all loaded assemblies for types implementing IDisposable
:
var disposableTypes =
from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
where typeof(IDisposable).IsAssignableFrom(t)
select t;
回答2:
Test your project with FxCop. It can catch all places where IDisposable objects are not disposed. You may need to do some work to disable all irrelevant FxCop rules, leaving only IDisposable-related rules.
For example, this is one of FxCop IDisposable rules: http://msdn.microsoft.com/en-us/library/ms182289%28VS.100%29.aspx
Note: you need to find both your own, .NET and third-party IDisposable objects which are not handled correctly.
回答3:
You can use NDepend to analyze your project and find all types that implement IDisposable.
Here´s the the cql query for the result
SELECT TYPES WHERE Implement "System.IDisposable"
回答4:
I think something like the code below might work. It would have to be adjusted to load the correct assembly if run from an external tool though.
Assembly asm = Assembly.GetExecutingAssembly();
foreach (Type type in asm.GetTypes())
{
if(type.GetInterface(typeof(IDisposable).FullName) != null)
{
// Store the list somewhere
}
}
回答5:
try this LINQ query:
var allIdisposibles = from Type t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterface(typeof(IDisposable).FullName) != null && t.IsClass
select t;