简体   繁体   中英

C# Generic methods / Polymorphism

I have the following code that I use to close a stream.

void CloseStream(Stream s)
{
    if (s != null)
        s.Close();
}

void CloseStream(HttpWebResponse s)
{
    if (s != null)
        s.Close();
}

void CloseStream(StreamReader s)
{
    if (s != null)
        s.Close();
}

The code works perfectly but I would like to refactor the 3 methods if it's possible. Ideally the method would look like that:

void CloseStream(Object obj)
{
    obj.Close();
}

But I cannot do obj.Close() because the Object class does not implements such a method. So I was wondering if any of you had any idea how to resolve it.

Thanks for your time, Kevin

All these 'streams' are disposable , so use Dispose() instead of Close() :

void CloseStream(IDisposable s)
{
    if (s != null)
        s.Dispose();
}

Also consider to use functionality built-in .Net Framework - using statement will automatically dispose disposable object without any additional calls to CloseStream :

using(StreamReader reader = File.OpenText(path))// create disposable here
{
    // use disposable
}

This code will automatically check if disposable is not null and dispose it at the end of using block. Code above block will compile into:

StreamReader reader = File.OpenText(path);

try
{
    // use disposable
}
finally // will be executed even in case of exception
{
   if (reader != null)
      reader.Dispose(); // internally calls Close()
}

All three classes implement IDisposable , and the Dispose method closes the underlying stream, so you can call that instead:

void CloseStream(IDisposable s)
{
    if (s != null)
        s.Dispose();
}

They should all implement IDisposable which implements Dispose (which does the same work as Close ).

So try:

void CloseStream(IDispsable obj)
{
    obj.Dispose();
}

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