C#中对于using的使用方式

导入命名空间

使用list需要导入 System.Collections.Generic;这个命名空间

using System.Collections.Generic;
using UnityEngine;
 
public class UsingTest : MonoBehaviour
{
     void Start()
    {
        List<int> intlist = new List<int>();
    }
}


省略类名

using UnityEngine;
using static UnityEngine.Mathf;
public class UsingTest : MonoBehaviour
{
    private void Start()
    {
        int a = 10;
        int b = 20;

        int c = Mathf.Max(a, b);
          c =Max(a, b);//这里在第二行引用了mathf,所以可以省略mathf,但是要注意重名

        Debug.Log(c);

    }
}


项目的全局引用using 使用gloal

对C#的语言有要求,好像是要C# 6.0以上上才可以,
当不支持的时候会提示
错误 CS8652 功能“全局 using 指令”当前为预览版且*不受支持*。要使用预览版功能,请使用“预览”语言版本。

//放到代码的开头,这样在全局都可以不添加这个命名空间
global using static UnityEngine.Mathf;
global using System.Collections;
global using System.Collections.Generic;
global using UnityEngine;


全局的隐式引用

感觉是这个不常用,就是很偏门,折磨人采用的东西。
不写。

使用命名空间的别名

第二行将System 的别名设置为sys,在这个文件里可以使用sys代替system

using UnityEngine;
using sys = System;

public class UsingTest : MonoBehaviour
{
    private void Start()
    {
        string path = "";
        var c = sys.IO.File.Exists(path);
    }
}

省内存,用完就会将对象销毁

using System.IO;
using UnityEngine;
 
public class UsingTest : MonoBehaviour
{
    private void Start()
    {
        using var strram = new MemoryStream();
        using var reader = new StreamReader(strram);

        reader.ReadToEnd();
    }

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值