简体   繁体   中英

How to find all Classes implementing IDisposable?

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?

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;

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.

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"

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
 }
}

try this LINQ query:

var allIdisposibles = from Type t in Assembly.GetExecutingAssembly().GetTypes()
                      where t.GetInterface(typeof(IDisposable).FullName) != null && t.IsClass
                      select t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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