我应该使用关键字为ObjectContext吗? [英] should i use using keyword for ObjectContext?
问题描述
try
{
//一些逻辑
}
finally
{
if(obj!= null)
{
obj.Dispose();
}
}
但是在观看实体框架教程时,遇到了这样做:
using(SampleBEntities db = new SampleBEntities()){// some logic here}
和SampleBEntities从ObjectContext继承,在MSDN中,ObjectContext不实现IDisposable?
解决方案是的,它实现
IDisposable
界面。public class ObjectContext:IDisposable
检查 MSDN
它有实现
IDisposable
接口的方法Dispose()
如果没有按照你所说的单独运行实现,它将不会编译。
使用语句 / p>
使用定义一个范围,其外面将放置一个对象或对象。
C#,通过.NET Framework常见语言运行时(CLR),自动释放用于存储不再需要的对象的内存。记忆的释放是非确定性的;每当CLR决定执行垃圾收集时,内存就会被释放。
using语句允许我们指定何时使用资源的对象应该释放它们。 提供给using语句的对象必须实现IDisposable接口。此接口提供Dispose方法,该方法应该释放对象的资源。
可以在达到使用语句的结尾时退出using语句,如果抛出异常,并且控件在语句结束之前留下语句块。
I have read somewhere on this site or CodeProject that good rule is if some class has implemented IDisposable interface than and only than you should use using keyword because using keyword translated into MSIL is try/finally block something like this:
try { //some logic } finally { if (obj != null) { obj.Dispose(); } }
but while watching tutorials for Entity Framework, I came across something like this:
using(SampleBEntities db = new SampleBEntities()){//some logic here}
and SampleBEntities inherits from ObjectContext and in the MSDN lib ObjectContext does not implement the IDisposable?
解决方案Yes it does implement
IDisposable
interface.public class ObjectContext : IDisposable
Check MSDN
It has methods
Dispose()
which comes from implementingIDisposable
interface.If it did not implement as you stated leave alone running, it won't even compile.
using statements
Using defines a scope, outside of which an object or objects will be disposed.
C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection.
The using statement allows us to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.
这篇关于我应该使用关键字为ObjectContext吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!