我应该使用使用关键字的ObjectContext的? [英] should i use using keyword for ObjectContext?

查看:91
本文介绍了我应该使用使用关键字的ObjectContext的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在什么地方在这个网站阅读或$ C $的CProject好规则是,如果某个类实现IDisposable接口相比,只比你应该使用关键字,因为使用关键字翻译成MSIL是try / finally块像这样使用:

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 come across something like this:

using(SampleBEntities db = new SampleBEntities()){//some logic here} 

和SampleBEntities从ObjectContext中,并在MSDN的lib ObjectContext的继承没有实现IDisposable?

and SampleBEntities inherits from ObjectContext and in the MSDN lib ObjectContext does not implement the IDisposable?

推荐答案

是的,它确实实现的IDisposable 接口。

Yes it does implement IDisposable interface.

public class ObjectContext : IDisposable

MSDN

它的方法的Dispose()这是从实施的IDisposable 接口。

It has methods Dispose() which comes from implementing IDisposable interface.

如果它,你说先不谈运行没有实现,它甚至不会编译。

If it did not implement as you stated leave alone running, it won't even compile.

using语句

使用限定范围,以外其中一个或多个对象将被设置

Using defines a scope, outside of which an object or objects will be disposed.

C#通过.NET Framework公共语言运行时(CLR),自动释放用于存储不再需要的对象的存储器。释放内存是不确定性;内存被释放每当CLR决定执行垃圾收集。

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.

using语句允许我们指定当使用资源的对象应该释放他们。 提供给using语句的对象必须实现IDisposable接口。该接口提供了Dispose方法,它应该释放该对象的资源。

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.

using语句,可以退出或者当到达using语句的结束,或者抛出一个异常,并控制离开语句块语句的结束之前。

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屋!

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