从.NET构造函数抛出异常 [英] Throwing exceptions from a constructor in .NET

查看:147
本文介绍了从.NET构造函数抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有当我从类似下面的构造函数抛出一个异常任何内存泄漏?

Are there any memory leaks when I throw an exception from a constructor like the following?

class Victim
{
    public string var1 = "asldslkjdlsakjdlksajdlksadlksajdlj";

    public Victim()
    {
        //throw new Exception("oops!");
    }
}

将失败的对象被垃圾收集器收集的?

Will the failing objects be collected by the garbage collector?

推荐答案

在这一般从没有内存泄漏的角度来看安全。但是,如果你分配非托管资源的类型从构造函数抛出异常是危险的。看看下面的例子

In general this is safe from the perspective of not leaking memory. But throwing exceptions from a constructor is dangerous if you allocate unmanaged resources in the type. Take the following example

public class Foo : IDisposable { 
  private IntPtr m_ptr;
  public Foo() {
    m_ptr = Marshal.AllocHGlobal(42);
    throw new Exception();
  }
  // Most of Idisposable implementation ommitted for brevity
  public void Dispose() {
    Marshal.FreeHGlobal(m_ptr);
  }
}

本课程将每次你想,即使你使用一个使用块创建时出现内存泄漏。例如,该泄漏内存。

This class will leak memory every time you try to create even if you use a using block. For instance, this leaks memory.

using ( var f = new Foo() ) {
  // Won't execute and Foo.Dispose is not called
}

这篇关于从.NET构造函数抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆