如果初始化程序抛出,是否构造一个对象? [英] Is an object constructed if an initializer throws?

查看:100
本文介绍了如果初始化程序抛出,是否构造一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读这篇文章 Jag Reeghal的博客,在我看来,他所建议的并不像使用对象初始化器那样。然后我意识到我真的不知道。

I was reading This Article over on Jag Reeghal's blog and It seemed to me that what he was suggesting was really not the same thing as using an object initializer. Then I realized that I didn't really know for sure.

当一个对象构造时,使用对象初始化器,其中一个intitializers抛出(可能是一个Null引用异常)...是实际构建的对象吗?这是否基本上像在构造函数中抛出异常?或者是完全构造的对象,然后初始化?

When an object is constructed, with object initializers, and one of those intitializers throws (maybe a Null Reference exception)... is the object actually constructed? Is this basically like an exception being thrown in the constructor? Or is the object fully constructed, and then initialized?

推荐答案

一个对象初始化语句,如 var x =新Foo {Property1 = 5}; 将被执行如下:

An object initilizer statement like var x = new Foo { Property1 = 5}; will be implemented as something like this:

Foo temp = new Foo();
temp.Property1 = 5;
x = temp;

如您所见,初始化器中的属性在构造对象后设置,但是该变量直到全部属性设置为止,所以如果抛出异常 ,即使捕获异常,构造的对象也会丢失(<该变量将保持 null 或其以前的任何值)。

As you can see, the properties in the initiallizer are set after the object is constructed, however the variable isn't set to the fully-initialized object until all the properties are set, so if an exception is thrown, the constructed object is lost even if the exception is caught (the variable will remain null or whatever value it had before).

这篇关于如果初始化程序抛出,是否构造一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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