c# - 使用 block : object initialization compiled into try block

标签 c# clr using try-finally

在我的项目中,我有一个对象,其构造函数可以抛出异常。所以我在整个过程中使用的代码如下:

MyObject obj = null;
try
{
    obj = new MyObject();
    obj.DoSomething();
}
finally
{
    if (obj != null)
        obj.Free();
}

Uses of "using" in C# 中所述,代码如下

using (MyObject obj = new MyObject())
{
    obj.DoSomething();
}

由 .NET CLR 转换为

{
    MyObject obj = new MyObject();
    try
    {
        obj.DoSomething();
    }
    finally
    {
        if (obj != null)
            ((IDisposable)obj).Dispose();
    }
}

问题是:我能否以某种方式让 CLR 将对象的构造函数放入 try block 中?

最佳答案

The question is: can I somehow make CLR put object's constructor into a try block?

没有。或者更确切地说,从资源管理的角度来看,这样做毫无意义。如果构造函数抛出异常,则不会有分配给 obj 的引用,因此将没有任何内容可调用 Dispose

重要的是,如果构造函数抛出异常,它会处理它分配的所有资源,因为调用者将无法处理。

关于c# - 使用 block : object initialization compiled into try block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19831627/

相关文章:

c# - 在 C# 中将 APRIL, 03/2013 字符串转换为 DateTime

c++-cli - 如何将 array<unsigned char> 转换为 unsigned char[]?

c# - IL 指令 "cpobj"是否适用于引用类型?

file - 在头文件中使用声明

c# - 在 Azure 函数中将事件作为参数传递时,TelemetryClient.StartOperation 始终失败

c# - MVC 5 DropDownList 说 DbContext 已释放?

c# - 为什么 CLS 要求抛出/捕获异常派生对象?

c# - 使用语句错误

c# - 为什么没有 ConfigurationManager?

c# - 为 .net web 应用程序寻找像 JMX 这样的管理