Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# using用法

作者:角落里哭泣   发布日期:2025-06-09   浏览:6

using System;

namespace UsingExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 使用 using 语句确保资源在使用后被正确释放
            using (System.IO.StreamReader file = new System.IO.StreamReader("file.txt"))
            {
                string line;
                while ((line = file.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            } // file 被自动关闭和释放

            // 使用 using 指令引入命名空间
            using System.Collections.Generic;

            List<int> numbers = new List<int>();
            numbers.Add(1);
            numbers.Add(2);
            numbers.Add(3);

            foreach (var num in numbers)
            {
                Console.WriteLine(num);
            }
        }
    }
}

解释说明:

  1. using 语句:用于确保实现了 IDisposable 接口的对象(如文件流、数据库连接等)在使用完毕后能够被正确释放。即使发生异常,也会调用对象的 Dispose 方法来释放资源。

    示例代码中,System.IO.StreamReader 对象在 using 块结束时会被自动关闭和释放。

  2. using 指令:用于引入命名空间,使得代码中可以直接使用命名空间中的类和其他成员,而无需每次都写完整的命名空间路径。

    示例代码中,using System.Collections.Generic; 引入了泛型集合的命名空间,因此可以直接使用 List<int> 而不需要写成 System.Collections.Generic.List<int>

上一篇:c# 向下取整

下一篇:c# newtonsoft.json

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站