“使用(实体obj =新实体())”的优点是什么?每次单独上课? [英] What is the advantage of "Using (Entity obj=new Entity())" every time with in individually in classes?

查看:52
本文介绍了“使用(实体obj =新实体())”的优点是什么?每次单独上课?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次在c#代码中使用此功能有什么好处。



What is advantage of using this in c# code for everytime.

using (Entities ctx = new Entities())
    {
        var rst = from tbl in ctx.TEST_TBL
                  select tbl;
        foreach (var tbl in rst)
        {
            Console.WriteLine(tbl.ID);
        }
    }

推荐答案

使用块做两件事:它会自动调用Dispose对代码退出块时创建的项目 - 出于任何原因 - 并且它仅将变量的范围限制为该cod块:您不能意外地引用Disposed对象,因为编译器一旦它超出范围就会抱怨它不再存在。



你应该总是处理任何实现IDisposable的对象,并且使用块可以轻松方便。
A using block does two things: it automatically calls Dispose on the item created whenever the code exits the block - for any reason at all - and it restricts the scope of the variable to that block of cod only: you cannot accidentally reference a Disposed object because the compiler will complain that it doesn't exist any more once it is out of scope.

You should always Dispose any object that implements IDisposable, and a using block makes that easy and convenient.


这篇关于“使用(实体obj =新实体())”的优点是什么?每次单独上课?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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