C#.NET各版本常用语法糖大全(C#3~C#10)|C/S开发框架

C#.NET各版本常用语法糖大全(C#3~C#10)

目录

引言

C# 3.0 语法糖

自动属性(Auto-Implemented Properties)

对象初始化器(Object Initializers)

集合初始化器(Collection Initializers)

匿名类型(Anonymous Types)

Lambda 表达式

隐式类型局部变量(var)

C# 4.0 语法糖

参数默认值和命名参数

C# 5.0 语法糖

async 和 await

C# 6.0 语法糖

空值合并运算符(Null Coalescing Operator ??)

字符串插值(String Interpolation)

空条件运算符(Null-Conditional Operator ?.)

扩展方法(Extensions)

C# 7.0 语法糖

元组和解构(Tuples and Deconstruction)

模式匹配(Pattern Matching)

C# 8.0 语法糖

using 声明

只读成员(Read-Only Members)

默认接口实现(Default Interface Methods)

静态本地函数(Static Local Functions)

C# 9.0 语法糖

记录类型(Record Types)

顶级语句(Top-Level Statements)

init 访问器(Init-Only Properties and Indexers)

模式和位置解构(Pattern Matching Enhancements for switch)

C# 10.0 语法糖

**目标类型的新表达式(Target-Typed New Expressions)

插值字符串增强(Interpolated String Enhancements)

结语

其他常用语法糖

表达式体属性

隐式类型局部变量(var 关键字)

Lambda 表达式

表达式体成员

字符串插值

空合并运算符(??)

名称空间别名

弃元(Discard)

可空类型

nameof 表达式

LINQ(Language Integrated Query)

条件编译指令

引言

C# 语言自诞生以来,随着每个版本的更新,不断引入新的语法糖,以简化代码编写,提高开发效率。语法糖使得代码更加简洁、可读,同时也减少了开发人员的负担。本文将按版本顺序汇总介绍 C# 各版本中引入的主要语法糖,并通过示例代码展示其使用方式。

C# 3.0 语法糖

自动属性(Auto-Implemented Properties)

自动属性简化了属性的声明,省去了手动编写字段和属性方法的繁琐。

C# 全选

//以前的写法

private int _myVar;

public int MyProperty

{

get { return _myVar; }

set { _myVar = value; }

}

//使用自动属性

public int MyProperty { get; set; }

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

对象初始化器(Object Initializers)

对象初始化器允许在声明对象时直接赋值属性,简化对象创建。

C# 全选

//以前的写法

Person p = new Person();

p.Name = "csframework.com";

p.Age = 18;

//使用对象初始化器

Person p = new Person { Name = "csframework.com", Age = 18 };

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

集合初始化器(Collection Initializers)

集合初始化器允许在声明集合时直接添加元素,简化集合创建。

C# 全选

//以前的写法

List numbers = new List();

numbers.Add(1);

numbers.Add(2);

//使用集合初始化器

List numbers = new List { 1, 2 };

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

匿名类型(Anonymous Types)

匿名类型提供了一种简单的方式来创建包含多个属性的对象,而不需要显式定义类型。

C# 全选

var person = new

{

Name = "csframework.com",

Age = 18

};

Console.WriteLine(person.Name);//输出"csframework.com"

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

Lambda 表达式

Lambda 表达式提供了一种简洁的方式来编写匿名方法。

C# 全选

//使用匿名方法

Func square = delegate (int x) { return x * x; };

//使用Lambda表达式

Func square = x => x * x;

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

隐式类型局部变量(var)

隐式类型局部变量使用 var 关键字声明变量,由编译器推断其类型。

C# 全选

var age = 10;//编译器推断为int

var name = "csframework.com";//编译器推断为string

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

C# 4.0 语法糖

参数默认值和命名参数

参数默认值允许为方法参数指定默认值。命名参数允许在调用方法时按名称指定参数,简化方法调用。

C# 全选

//按顺序传递参数

test.DisplayGreeting("csframework.com", 23, "ZhuHai");

//调用时,可以使用命名参数来指定特定参数的值

test.DisplayGreeting(name: "csframework.com", city: "ZhuHai");

Console.ReadKey();

public static class test

{

public static void DisplayGreeting(string name, int age = 35, string city = "ZhuHai")

{

//输出:Hello,csframework.com.You are35years old and live inZhuHai.

Console.WriteLine($"Hello,{name}.You are{age}years old and live in{city}.");

}

}

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

C# 5.0 语法糖

async 和 await

async 和 await 关键字简化了异步编程,提供了类似同步代码的编程体验。

C# 全选

public async Task FetchDataAsync()

{

using (HttpClient client = new HttpClient())

{

string result = await client.GetStringAsync("https://www.example.com/test/data");

return result;

}

}

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

C# 6.0 语法糖

空值合并运算符(Null Coalescing Operator ??)

空值合并运算符提供了一种简洁的方式来处理可能为空的变量。

C# 全选

string name = null;

string RegName = name ?? "csframework.com";

Console.WriteLine(RegName);//输出"csframework.com"

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

字符串插值(String Interpolation)

字符串插值提供了一种更简洁、更可读的字符串格式化方式。

C# 全选

string name = "csframework.com";

int age = 18;

//Hello,my name is csframework.com and I am 18 years old.

string greeting = $"Hello,my name is {name} and I am {age} years old.";

Console.WriteLine(greeting);

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

空条件运算符(Null-Conditional Operator ?.)

空条件运算符简化了对可能为空的对象成员的访问。

C# 全选

Employee employee = new Employee();

string departmentName = employee?.Department?.Name ?? "Unknown"; //输出Unknow

Console.WriteLine(departmentName);

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

C# 全选

Employee employee = null;

string departmentName = employee?.Department?.Name ?? "Unknown"; //输出Unknow

Console.WriteLine(departmentName);

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

扩展方法(Extensions)

扩展方法允许为现有类型添加新方法,而无需修改类型的定义。

C# 全选

//使用扩展方法

var transform = new Transform();

transform.Hide();

transform.Show();

//使用现有的方法

transform.SetActive(false);

transform.SetActive(true);

Console.ReadKey();

//实体类

public class Transform

{

public Transform SetActive(bool value)

{

Console.WriteLine(value);

return new Transform();

}

}

//扩展类

public static class TransformExtensions

{

public static Transform Hide(this Transform transform) => transform.SetActive(false);

public static Transform Show(this Transform transform) => transform.SetActive(true);

}

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

C# 7.0 语法糖

元组和解构(Tuples and Deconstruction)

元组提供了一种轻量级的数据结构,解构简化了元组元素的访问。

C# 全选

//创建一个元组

var person = ("csframework.com", 18);

//解构元组:封装

var (name, age) = person;

Console.WriteLine($"Name:{name},Age:{age}");//Name:csframework.com,Age:18

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

模式匹配(Pattern Matching)

模式匹配增强了类型检查和转换的能力。

C# 全选

object obj = 123;

//类型检查和转换

if (obj is int i)

{

Console.WriteLine($"Integer:{i}");

}

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

C# 8.0 语法糖

using 声明

using 声明简化了资源管理,减少了嵌套。

C# 全选

//C#8.0之前的写法

using (var stream = new FileStream("file.txt", FileMode.Open))

{

//使用stream

stream.Write();

}

//C#8.0及更高版本的写法

using var stream = new FileStream("file.txt", FileMode.Open);

//使用stream

stream.Write();

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

只读成员(Read-Only Members)

只读成员确保结构体成员不可变。

C# 全选

public struct Point

{

public double X { get; }

public double Y { get; }

//构造器:编译通过

public Point(double x, double y)

{

X = x;

Y = y;

}

//方法:编译不通过

public void Set(double x, double y)

{

X = x;

Y = y;

}

}

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

默认接口实现(Default Interface Methods)

默认接口实现允许在接口中提供默认方法实现。

C# 全选

public interface ILogger

{

void Log(LogLevel level, string message)

{

//默认实现

Console.WriteLine($"Log:{level}-{message}");

}

}

public class ConsoleLogger : ILogger

{

//可以选择不实现Log方法,使用默认实现

}

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

静态本地函数(Static Local Functions)

静态本地函数确保本地函数不捕获任何外围变量。

C# 全选

//方法

void MyMethod()

{

static void LocalFunction()

{

//这是一个静态本地函数

Console.WriteLine("这是一个静态本地函数。");

}

//调用静态本地函数

LocalFunction();

}

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

C# 9.0 语法糖

记录类型(Record Types)

记录类型简化了不可变数据结构的定义。

C# 全选

var person = new Person("csframework.com", 18);

Console.WriteLine(person);//输出Person{Name=csframework.com,Age=18}

//定义记录类型

public record Person(string Name, int Age);

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

顶级语句(Top-Level Statements)

顶级语句简化了程序的入口点,省去了 Main 方法的定义。

C# 全选

using System;

using System.Xml.Linq;

Console.WriteLine("Hello, csframework.com");

Console.ReadKey();

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

init 访问器(Init-Only Properties and Indexers)

init 访问器允许在对象初始化时设置属性,而初始化后属性变为只读。

C# 全选

var point = new Point { X = 0.0, Y = 0.0 };

point.X = 100; //编译不通过

//结构

public struct Point

{

public double X { get; init; }

public double Y { get; init; }

}

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

模式和位置解构(Pattern Matching Enhancements for switch)

模式匹配增强了 switch 表达式的功能。

C# 全选

public static string GetSeason(DateTime date) => date.Month switch

{

12 or 1 or 2 => "Winter",

3 or 4 or 5 => "Spring",

6 or 7 or 8 => "Summer",

9 or 10 or 11 => "Autumn",

_ => "Unknown",//defaut 弃元

}

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

C# 10.0 语法糖

**目标类型的新表达式(Target-Typed New Expressions)

** 目标类型的新表达式简化了对象创建,省略了类型名。

C# 全选

Point p = new(0.0, 0.0);

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

插值字符串增强(Interpolated String Enhancements)

插值字符串增强了表达式的灵活性,可以在插值表达式中调用方法。

C# 全选

var name = "csframework.com";

//语法:$和{}

var message = $"Hello,{name.ToLower()}!";

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

结语

随着 C# 语言的发展,每个版本都为开发者带来了新的语法糖,使代码编写更加简洁、直观。这些语法糖不仅提高了代码的可读性,还提升了开发效率。通过本文的介绍,希望能帮助你更好地理解和应用这些语法糖,从而在实际开发中充分发挥它们的优势。

其他常用语法糖

表达式体属性

使用 => 运算符定义属性的 getter 或 setter。

C# 全选

public string FullName => FirstName + " " + LastName;

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

隐式类型局部变量(var 关键字)

编译器根据初始化表达式推断变量的类型。

C# 全选

var number = 42; // 推断为 int 类型

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

Lambda 表达式

定义匿名函数的简洁方式。

C# 全选

Func add = (x, y) => x + y;

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

表达式体成员

用于方法和委托。

C# 全选

public int Square(int x) => x * x;

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

字符串插值

在字符串中嵌入变量或表达式的值。

C# 全选

string message = $"Hello, {name}!";

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

空合并运算符(??)

当左侧操作数为 null 时,返回右侧操作数的值。

C# 全选

string result = value ?? "Default Value";

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

名称空间别名

允许你为名称空间或类型定义别名,以简化代码中的引用。

C# 全选

using System.Collections.Generic;

using List = System.Collections.Generic.List; // 定义别名

List numbers = new List(); // 使用别名

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

弃元(Discard)

使用下划线 _ 作为占位符来表示不关心的变量值,这在解构赋值或模式匹配中特别有用。

C# 全选

var (first, _) = GetTuple(); // 只关心第一个值,忽略第二个值

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

可空类型

使用可空类型(如 int?)可以表示值类型的空值,避免了使用默认值来表示空值的问题。

C# 全选

int? age = null;

if (age.HasValue)

{

// 处理非空值的情况

}

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

nameof 表达式

返回变量、类型或成员的名称作为字符串,主要用于异常消息、日志记录等。

C# 全选

string name = "Alice";

Console.WriteLine(nameof(name)); // 输出 "name"

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

LINQ(Language Integrated Query)

允许你在 C# 中直接编写查询语句,而无需使用额外的查询语言。

C# 全选

var query = from p in people

where p.Age > 18

select p.Name;

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

条件编译指令

使用如 #if, #else, #endif 等预处理指令,可以根据不同的编译条件包含或排除代码块。这对于跨平台开发或调试非常有用。

C# 全选

#if DEBUG

Console.WriteLine("Debug mode is enabled.");

#endif

专注.NET技术、C/S架构开发框架软件

C/S框架网 - C/S开发框架

扫一扫加作者微信