C#中关于Using关键字的使用技巧!

C# · 2024-01-05 · 1906 人浏览
C#中关于Using关键字的使用技巧!

CSharp-Tutorial.png

  • 引入命名空间(Using NameSpace)
  • 静态引入命名空间(Using Static)
  • 全局引入命名空间(Global Usings)
  • 隐式引入命名空间(Immlicit Usings)
  • Using操作可释放资源(Using IDisposable)

Using NameSpace

🚀:对命名空间的引用

using System;
using System.Collections.Generic;
using System.Linq;

Console.WriteLine("Hello,Mindev!");
var list = new List<int>();
var Sum = list.Sum();

Using Static

1、通常方式(常用)

using System.Math;

Math.Cos(10);
Math.Round(0.6);
Math.Pow(4,2);

2、静态使用(不常用)

🚀:因为会将类中所有静态方法全部暴露出来

using static System.Math;
Cos(10);
Pow(2,5);

Global Usings

🚀:全局使用命名空间,即在using前加上global,程序集中的每个文件都会

// 文件A
global using System;
global using Linq;
global using System.Collections.Generic;
global using System.Math;
// 文件B
Console.WriteLine("Hello,Mindev!");
var list = new List<int>();
var sum = list.Sum();

Immlicit Usings

🚀:在AllAboutUsings.csproj文件中,找到\<ImplicitUsings>disalbe\</ImplicitUsings>,将标签中的disable改为enable,即表示自动引入。

<Projet Sdk="Microsoft.Net.Sdk">
    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
        <!-- <ImplicitUsings>disable</ImplicitUsings> -->
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>
</Project>

📚:在路径"obj -> Debug -> net6.0 -> refint"目录下找到文件"AllAboutUsings.GlobalUsings.g.cs",在此文件中可以找到自动引用的命名空间。

// <auto-generated/>
global using global::System;
global using global::System.Collections..Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;

🔖:追加隐士引用(在之前的基础上,即Projiect标签中),编译后就可以在"AllAboutUsings.GlobalUsings.g.cs"文件中查看到引入的命名空间了。

<iteamGroup>
    <Using Include="System.Text.Json" />
</iteamGroup>

Using Alias

🚀:在引入命名空间时,可以将命名空间起单独的别名,示例代码如下。

// using System;
using Sys = System;
using IO = System.IO;
Sys.Console.WriteLine("Hello,Mindev!");
// 引入Student类
using Stu = School.Class.Student;
Stu student = new Stu();

Using IDisposable

🚀:using关键字操作可释放资源,示例代码如下。

using System.Text;
using (var stream = new FileStream("路径",FileMode.Open))
{
    using (var reader = new StreamReader(stream,Encoding.UTF8))
    {
        reader.ReadToEnd();
    }
}

⌛:可以将上面的代码进行整理,在.NET8中,可以改为以下代码形式。

// 精简型代码
using System.Text;
using var stream = new FileStream("Path",FileMode.Open);
using var reader = new StreamReader(stream,Encoding.UTF8);
reader.ReadToEnd();
C#