简体   繁体   English

C#通用方法/多态性

[英]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. 代码完美无缺,但我想重构3种方法,如果可能的话。 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. 但是我不能做obj.Close()因为Object类没有实现这样的方法。 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() : 所有这些'流'都是一次性的 ,所以使用Dispose()而不是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 : 还要考虑使用内置的功能.Net Framework - using语句将自动处理一次性对象,而无需对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. 此代码将自动检查一次性是否为null ,并在using块结束时将其丢弃。 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: 这三个类都实现了IDisposableDispose方法关闭了底层流,因此您可以调用它:

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

They should all implement IDisposable which implements Dispose (which does the same work as Close ). 它们都应该实现实现Dispose IDisposable (它与Close完成相同的工作)。

So try: 所以尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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