C#自学笔记:语法糖

特殊语法

var隐式类型

var是一种特殊的变量类型

它可以用来表示任意类型的变量

  • 注意:
  1. var不能作为类的成员只能用于临时变量申明时,也就是一般写在函数语句块中
  2. var必须初始化
var i = 5;
var s = "123";
var array = new int[]{1, 2, 3, 4, 5};
var list = new List<int>();

设置对象初始值

申明对象时

可以通过直接写大括号的形式初始化公共成员变量和属性

  • 用无参构造函数new对象时,可以省略(),直接用大括号初始化成员变量和属性
class Person
{
    private int money;
    public bool Sex;
    public string Name
    {
        get;
        set;
    }
    public int Age
    {
        get;
        set;
    }
    //有参构造时new对象就需要加上括号
    public Person(int money)
    {
        this.money = money;
    }
}
//使用
Person p = new Person{Sex = true, Age = "18", Name = "柠凉"};

也可以加上括号,无影响

设置集合初始值

申明集合对象时

也可以通过大括号直接初始化内部属性

int[] array = new int[]{1, 2, 3, 4, 5};

List<int> listInt = new List<int>{1, 2, 3, 4, 5};

List<Person> listPerson = new List<Person> {
    new Person(200),
    new Person(100) {Age = 10},
    new Person(1) {Sex = true, Name = " 柠凉"}
};

Dictionary<int, string> dic = new Dictionary<int, string> {
    {1, "123"},
    {2, "222"},
};

匿名类型(不建议使用)

var变量可以申明为自定义的匿名类型
var v = new {age = 10, money = 11, name = "小明"};

可空类型 ?

  1. 值类型是不能赋值为空的
  2. 申明时在值类型后面加?可以赋值为空
    • int? c = null;
  3. 判断是否为空
    • if (c.HasValue)
  4. 安全获取可空类型值
    • int? value = null
    1. 如果为空默认返回值类型的默认值
      • value.GetValueOrDefault()
    2. 也可以指定一个默认值
      • value.GetValueOrDefault(100)
      • 如果value为空,则获取100,但是并不是赋值
//引用类型
object o = null;
o?.ToString();

int[] arrayInt = null;
Console.WriteLine(arrayInt?[0]);
//?[]只判断整个数组是否为空,不判断当前位置,如果当前位置越界仍会报错

Action action = null;
action?.Invoke();

空合并操作符 ??

空合并操作符??

左边值??右边值

如果左边值为null就返回右边值否则返回左边值

只要是可以为null的类型都能用

int? intV = null;
int intI = intV == null ? 100 : intV.Value;
intI = intV ?? 100;
//如果intV不等于空,则赋值给intI,如果为空,则赋值为100

内插字符串 $

关键符号:$

用$来构造字符串,让字符串中可以拼接变量

string name = "柠凉";
int age = 18;
Console.WriteLine($"努力学习开发,{name}, 年龄:{age}");

using语句

using 语句允许程序员指定使用资源的对象何时应该释放它们。提供给 using 语句的对象必须实现 IDisposable 接口。该接口提供了 Dispose 方法,该方法应该释放对象的资源。

例子:这些是等价的:

SomeDisposableType u = new SomeDisposableType();
try {
    OperateOnType(u);
}
finally {
    if (u != null) {
        ((IDisposable)u).Dispose();
    }
}
using (SomeDisposableType u = new SomeDisposableType()) 
{
    OperateOnType(u);
}

模式匹配

模式匹配本质上是一种表达式判定工具:用以检查一个对象是否与某种“模式”相吻合,如果吻合,还允许对其分解、绑定成员变量。这可以是类型检查、常量判断、属性结构匹配等。

例子:

传统C#写法:

if (person != null && person.Age >= 18 && person is Employee
    && ((Employee)person).YearsAtCompany > 5) {
    // 处理逻辑
}

模式匹配写法:

if (person is Employee { Age: >= 18, YearsAtCompany: > 5 }) {
    // 处理逻辑
}

传统C#写法:

if (ModuleBigVersionInfoList != null && ModuleBigVersionInfoList.Count > 0)

模式匹配写法:

if (ModuleBigVersionInfoList is { Count: > 0 })

分解说明:

  1. is关键字:用于类型检查和模式匹配
  2. { Count: > 0 }:这是 属性模式 的语法
    • { Count: ... }:检查对象的 Count属性
    • > 0:关系模式,表示 Count必须大于 0
  3. 整个表达式会先检查 ModuleBigVersionInfoList是否为 null,如果不是 null再检查 Count是否大于 0
posted @ 2025-08-27 17:24  柠凉w  阅读(10)  评论(0)    收藏  举报