DotNet · 2022年3月16日

C# 的 using 与 VB 的 using 语句-非库引入

这里的using使用在语句中,不是C#类文件顶上的using和vb.net类文件顶上的import

C# 中,using 关键字可以创建 using 指令和 using 语句,分别对应 VB 中的 Imports 语句和 using 语句

C# 和 VB 中的 using 语句作用是:定义一个范围,将在此范围之外释放一个或多个对象。

.NET Framework 公共语言运行库 (CLR) 会自动释放用于存储不再需要的对象的内存,但是通常由程序来尽快释放不需要内存更好一些,using 就实现了由程序来控制什么时候释放内存。

看示例(根据微软示例修改),使用 using 的语句调用了 IDisposable.Dispose,而未使用 using 的则没有调用。为 using 语句提供的对象必须实现 IDisposable 接口。

<%@ Page Language=”C#” Debug=”true” %>
<script runat=”server”>
    class C : IDisposable
    {
        Label lb;
       
        public C(Label Alb)
        {
            lb = Alb;
        }
       
        public void UseLimitedResource()
        {
            lb.Text += “Using limited resource…<br />”;
        }
       
        void IDisposable.Dispose()
        {
            lb.Text += “Disposing limited resource.<br />”;
        }
    }
   
    void Page_Load(object sender, EventArgs e)
    {
        using (C c = new C(lb))
        {
            c.UseLimitedResource();
        }
        lb.Text += “Now outside using statement.<br />”;
   
        C c2 = new C(lb2);
        c2.UseLimitedResource();
    }
</script>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
    <title>Using 语句(C#)</title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
    <asp:Label ID=”lb” runat=”server”></asp:Label>
    <hr />
    <asp:Label ID=”lb2″ runat=”server”></asp:Label>
    </div>
    </form>
</body>
</html>

将显示

Using limited resource…
Disposing limited resource.
Now outside using statement.


Using limited resource…

Using 块的工作方式类似于 Try…Finally 构造,在该构造中,Try 块使用资源,而 Finally 块释放资源。因此,不管您如何退出块,Using 块都可确保资源的释放。即使发生未处理的异常(除 StackOverflowException 外),也是如此。

最新电影,电视剧,尽在午夜剧场

电影电视剧午夜不寂寞