如果我的结构体实现了IDisposable,那么在using语句中使用它时会被装箱吗? [英] If my struct implements IDisposable will it be boxed when used in a using statement?

查看:70
本文介绍了如果我的结构体实现了IDisposable,那么在using语句中使用它时会被装箱吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的结构实现了IDisposable,那么在使用using语句时将其装箱吗?

If my struct implements IDisposable will it be boxed when used in a using statement?

谢谢

编辑:
此timedlock是一个结构并实现Idisposable。
http://www.interact-sw.co .uk / iangblog / 2004/04/26 / yetmoretimedlocking

编辑2:看着IL,如果您的结构公开公开了Dispose(),如果您忘记调用Dispose()(例如,您未使用 using语句),则当该结构的实例超出范围时,编译器将调用Dispose?

Edit 2: Looking at the IL it seems If your struct exposes Dispose() as public, the compiler calls Dispose when an instance of the struct goes out of scope if you forget to call Dispose() (for example, you are not using the "using" statement)?

推荐答案

每个埃里克·利珀特(Eric Lippert)

对IDisposable的调用。结构上的Dispose生成为受约束的虚拟调用,大多数情况下不会将值装箱。

A call to IDisposable.Dispose on a struct is generated as a constrained virtual call, which most of the time does NOT box the value.

如果值类型未实现虚拟方法,则对值类型的约束虚拟调用仅将值装箱。值类型无法实现虚拟方法的唯一情况是该方法为ToString并由基类System.ValueType实现。

A constrained virtual call on a value type only boxes the value if the virtual method is NOT implemented by the type. The only circumstances under which a virtual method can be unimplemented by the value type is when the method is, say, ToString, and implemented by the base class, System.ValueType.

有关更多详细信息,请参见CLI文档Partition III的2.1节。

See section 2.1 of Partition III of the CLI documentation for more detail.

这篇关于如果我的结构体实现了IDisposable,那么在using语句中使用它时会被装箱吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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