简体   繁体   English

使用block:将对象初始化编译成try块

[英]Using block: object initialization compiled into try block

In my project I have an object whose constructor can throw. 在我的项目中,我有一个构造函数可以抛出的对象。 So the code I'm using all across is as follows: 所以我正在使用的代码如下:

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

As meantioned in Uses of "using" in C# , the code like 正如在C#使用“使用”一样,代码就像

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

is converted by the .NET CLR to 由.NET CLR转换为

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

The question is: can I somehow make CLR put object's constructor into a try block? 问题是:我可以以某种方式使CLR将对象的构造函数放入try块中吗?

The question is: can I somehow make CLR put object's constructor into a try block? 问题是:我可以以某种方式使CLR将对象的构造函数放入try块中吗?

No. Or rather, it's pointless to do so, from a resource management perspective. 不,或者说,从资源管理的角度来看,这样做毫无意义。 If an exception is thrown by the constructor, then there won't be a reference assigned to obj , so there'll be nothing to call Dispose on. 如果构造函数抛出异常,那么就不会有一个分配给obj的引用,所以没有什么可以调用Dispose

It's critical that if a constructor throws an exception, it disposes of any resources it allocated, as the caller won't be able to. 至关重要的是,如果构造函数抛出异常,它会处理它分配的任何资源,因为调用者将无法执行。

No you can not do that as, this is using and it works in that way. 不,你不能这样做,这是using ,它以这种方式工作。 You have to write the code you need by yourself 您必须自己编写所需的代码

Worth mentioning that having exception in ctor of the type, is not a good idea at all, so may be , if this is possible move the code that can potentially raise an exception to another place. 值得一提的是,在类型的ctor中有异常,根本不是一个好主意,所以如果可能的话,可能会将可能引发异常的代码移动到另一个地方。 It's better to have one more method and constrain consumer of your type to call that explicitly in order to achieve something and having control over situation, then having situations like you describe. 最好还有一个方法,并限制你的类型的消费者明确地调用它来实现某些事情并控制情况,然后像你描述的情况那样。

In general, use ctor only for construction of the instance of a given type and initialization of internal values. 通常,使用ctor仅用于构造给定类型的实例和内部值的初始化。

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

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