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

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

问题描述

我已经在本站或CodeProject上的某个地方看到,如果某些类实现了IDisposable接口,而不仅仅是使用关键字,则使用关键字转换成MSIL,那么这个规则就是很好的规则。try / finally会阻止这样的一个例子:

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

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