c# - 使用 C# 处理 - 完整实现

标签 c# dispose using

如何在实现 IDisposable 的类中对 MemoryStream 对象使用“using”后实现 Dispose 方法?

public class ControlToByte :IDisposable
{
    public static byte[] GetByte(object control)
    {
        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
        { //do something here  } 
public void Dispose()
    {
       //how do you dispose of memorystream object?
    }

最佳答案

您不必实现 IDispose,也不必显式调用 Disposeusing block 将确保在完成后释放 MemoryStreamusing block 实际上像 try/finally block 一样工作。像这样的东西:

{
    System.IO.MemoryStream memoryStream = null;

    try
    {
        memoryStream = new System.IO.MemoryStream();
        //....your code
    }
    finally
    {
        if (memoryStream != null) //this check may be optmized away
            memoryStream.Dispose();
    }
}

using C#

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

在你当前的代码中,你正在你的类 ControlToByte 上实现 IDisposable,如果你想在 ControlToByte 中处理资源,这将很有用.如图所示,您不需要为您的类实现 IDisposable

关于c# - 使用 C# 处理 - 完整实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16055843/

相关文章:

c# - 我无法打开 .xlsx 文件

c++ - 用原始类型替换模板类

c# - xamarin.forms-页面底部的“滑动”信息框

c# - 在 using block 中间返回

c# - 处理 SQL 连接

sharepoint - 使用从函数返回的 SPListItemCollection 是否会重新打开 SPWeb?

c# - 异常处理(矛盾的文档/尝试最终与使用)

c++ - 是否有私有(private)使用名称=类型;

c# - DataGridViewCheckboxCell 的背景色

c# - 返回带有模型和查询字符串的 View