当前位置: 首页 > news >正文

C#基础16-C#6-C#9新特性

零、文章目录

C#基础16-C#6-C#9新特性

1、C#6新特性

(1)表达式属性(Expression-bodied Properties)
  • 作用:简化只读属性的定义,用Lambda语法替代传统get访问器。
// C# 6之前
public string FullName {get { return $"{FirstName} {LastName}"; }
}// C# 6表达式属性
public string FullName => $"{FirstName} {LastName}";  // 一行完成
(2)自动属性初始化器(Auto-Property Initializers)
  • 作用:声明属性时直接赋默认值,无需构造函数。
public class Config {public int MaxRetryCount { get; set; } = 3;     // 直接初始化public List<string> LogTypes { get; } = new List<string>(); // 只读集合初始化
}
(3)字符串插值(String Interpolation)
  • 作用:替代string.Format,内嵌变量更直观。
var user = new { Name = "Alice", Age = 30 };
// 旧写法
var oldStr = string.Format("Name: {0}, Age: {1}", user.Name, user.Age);
// C# 6新写法
var newStr = $"Name: {user.Name}, Age: {user.Age}";  // 直接嵌入变量
(4)空值条件运算符(Null-Conditional Operator ?.
  • 作用:安全访问可能为null的对象成员,避免NullReferenceException
public class Order {public Customer Customer { get; set; }
}
public class Customer {public string Address { get; set; }
}Order order = null;
// 安全访问链:若order为null,则返回null而非异常
string address = order?.Customer?.Address;  // 结果:null
(5)异常过滤器(Exception Filters)
  • 作用:根据条件决定是否捕获异常,不满足条件时异常继续向上传递。
try {File.ReadAllText("missing.txt");
}
catch (IOException ex) when (ex.Message.Contains("not found")) { // 仅当异常消息包含"not found"时捕获Console.WriteLine("文件未找到,记录日志");// 此处不会吞没异常,其他异常类型或条件不匹配时仍会抛出
}
(6)索引初始化器(Index Initializers)
  • 作用:简化字典和索引器集合的初始化语法。
// 旧写法
var dict1 = new Dictionary<int, string>();
dict1.Add(1, "One");
dict1.Add(2, "Two");// C# 6新写法
var dict2 = new Dictionary<int, string> {[1] = "One",   // 类似对象初始化语法[2] = "Two"
};
(7)nameof 表达式
  • 作用:生成变量/类型名称字符串,避免硬编码。
public void Validate(string input) {if (input == null) throw new ArgumentNullException(nameof(input)); // 输出"input"
}
(8)静态导入(using static
  • 作用:直接使用静态类成员,无需类名前缀。
using static System.Math;
double radius = 10;
double area = PI * Pow(radius, 2);  // 直接调用Math.PI和Math.Pow

2、C#7新特性

(1)元组(Tuples)与解构
  • 作用:支持方法返回多个值,简化数据组合与分解。
// 定义元组(显式命名成员)
public (string Name, int Age) GetUserInfo() => ("Alice", 30);// 使用元组
var user = GetUserInfo();
Console.WriteLine($"Name: {user.Name}, Age: {user.Age}"); // 直接访问命名成员// 解构元组
(string name, int age) = GetUserInfo();  // 解构为独立变量
Console.WriteLine($"解构结果:{name}, {age}");
(2)模式匹配(Pattern Matching)
  • 作用:通过isswitch增强类型检查与条件分支。
// 类型模式 + 条件过滤
object obj = -10;
switch (obj) {case int i when i > 0:  // 匹配正数Console.WriteLine($"正数: {i}");break;case string s:          // 匹配字符串Console.WriteLine($"字符串: {s}");break;case null:              // 匹配nullConsole.WriteLine("空值");break;default:                // 默认分支Console.WriteLine("未知类型");break;
}
(3)本地函数(Local Functions)
  • 作用:在方法内部定义辅助函数,封装复杂逻辑。
public double CalculateCircleArea(double radius) {// 本地函数:验证半径有效性void ValidateRadius(double r) {if (r <= 0) throw new ArgumentException("半径必须大于0");}ValidateRadius(radius);return Math.PI * Math.Pow(radius, 2);
}
(4)out变量声明优化
  • 直接在参数位置声明变量
if (int.TryParse("123", out int result)) {  // 无需预先声明Console.WriteLine($"解析成功: {result}");
}
(5)throw表达式
  • 在表达式上下文中抛出异常
string config = GetConfig() ?? throw new InvalidOperationException("配置为空");
(6)表达式体成员扩展
  • 支持构造函数、属性访问器等:
public class Logger {private string _logPath;public Logger(string path) => _logPath = path;  // 表达式体构造函数public string LogPath => _logPath;              // 表达式体只读属性
}
(7)ref局部变量与返回
  • 减少值拷贝,提升性能:
public ref int FindValue(int[] array, int target) {for (int i = 0; i < array.Length; i++) {if (array[i] == target) return ref array[i];  // 返回引用}throw new Exception("未找到");
}// 调用
int[] numbers = { 1, 2, 3 };
ref int numRef = ref FindValue(numbers, 2);
numRef = 10;  // 直接修改数组元素(原数组变为 [1,10,3])
(8)ValueTask<T>异步返回
  • 避免Task分配开销(需引用System.Threading.Tasks.Extensions
public async ValueTask<int> GetCachedDataAsync() {if (_cache.TryGetValue("key", out int data)) return data;  // 同步返回缓存值return await FetchDataAsync();  // 异步获取数据
}

3、C#8新特性

(1)可空引用类型(Nullable Reference Types)
  • 作用:显式区分可空与非空引用类型,减少空引用异常
#nullable enable  // 启用可空检查 public class UserProfile
{public string Name { get; }          // 非空(编译警告)public string? Description { get; }  // 显式可空 public UserProfile(string name, string? description){Name = name;Description = description;  // 安全赋值 }
}// 使用示例 
var profile = new UserProfile("Alice", null);
int length = profile.Description?.Length ?? 0;  // 安全访问 
(2)异步流(Async Streams)
  • 作用:通过IAsyncEnumerable<T>实现异步数据流处理
async IAsyncEnumerable<int> FetchSensorDataAsync()
{for (int i = 0; i < 5; i++){await Task.Delay(500);  // 模拟异步操作yield return Random.Shared.Next(1, 100);}
}// 消费异步流
await foreach (var data in FetchSensorDataAsync())
{Console.WriteLine($"实时数据: {data}");
}
(3)范围和索引(Ranges and Indices)
  • 作用:简化集合切片操作
var numbers = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };// 索引
Index lastIndex = ^1;  
Console.WriteLine($"最后元素: {numbers[lastIndex]}");  // 输出 9// 范围
Range middle = 3..^2;  
var subset = numbers[middle];  // 获取 [3,4,5,6,7]
Console.WriteLine($"子集: {string.Join(",", subset)}");// 替代Substring
string text = "Hello World";
Console.WriteLine(text[6..]);  // 输出 "World"
(4)接口默认方法(Default Interface Members)
  • 作用:允许接口提供方法实现,避免破坏现有实现
public interface ILogger
{void Log(string message) => Console.WriteLine(message);  // 默认实现 void LogError(string error);
}public class FileLogger : ILogger
{// 只需实现LogErrorpublic void LogError(string error) => File.WriteAllText("error.log", error);
}// 使用默认方法 
ILogger logger = new FileLogger();
logger.Log("常规日志");  // 自动调用接口默认实现 
(5)Switch表达式(Switch Expressions)
  • 作用:简化模式匹配语法,返回值可直接使用
public static string GetTemperatureLevel(float temp) => temp switch
{< 0 => "冰冻",>= 0 and < 15 => "寒冷",>= 15 and < 25 => "舒适",>= 25 and < 35 => "温暖",>= 35 => "炎热",_ => "未知"  // 默认分支 
};// 使用示例 
Console.WriteLine(GetTemperatureLevel(28));  // 输出 "温暖"
(6)Using声明优化(Using Declarations)
  • 作用:自动释放资源,无需显式代码块
void ProcessFile(string path)
{using var reader = new StreamReader(path);  // 自动在作用域结束时释放string content = reader.ReadToEnd();Console.WriteLine($"文件长度: {content.Length}");
}  // 此处自动调用reader.Dispose()
(7)模式匹配增强(Recursive Patterns)
  • 作用:支持嵌套属性匹配
public double CalculateArea(object shape) => shape switch
{Circle { Radius: var r } => Math.PI * r * r,                  // 解构半径 Rectangle { Width: > 0, Height: > 0 } r => r.Width * r.Height, // 条件匹配 Triangle points when points.Vertices.Count == 3 => ...,       // when条件过滤 _ => throw new ArgumentException("未知形状")
};
(8)目标类型new表达式(Target-typed new)
  • 作用:省略类型声明
// 旧写法 
Dictionary<string, int> dict = new Dictionary<string, int>();// C#8新写法 
Dictionary<string, int> dict = new();  // 自动推导类型// 数组初始化 
Point[] points = { new(1, 2), new(3, 4) };  // 无需重复声明类型

4、C#9新特性

(1)仅初始化属性(Init-only Properties)
  • 作用:允许属性在对象初始化时赋值,之后变为只读状态
public class Person
{public string FirstName { get; init; }  // 只能在初始化时赋值public string LastName { get; init; }
}// 使用 
var person = new Person { FirstName = "Alice", LastName = "Smith" };
// person.FirstName = "Bob";  // 编译错误:属性只读
(2)记录类型(Record Types)
  • 作用:创建不可变数据类型,自动实现值相等性检查和拷贝逻辑
public record Book(string Title, string Author);  // 一行定义不可变记录 // 使用 
var book1 = new Book("C# Guide", "Microsoft");
var book2 = book1 with { Title = "Advanced C#" };  // 使用with创建副本 
Console.WriteLine(book1 == book2);  // 自动实现值相等性检查(输出:false)
(3)顶级语句(Top-level Programs)
  • 作用:简化控制台程序入口,无需显式定义Main方法
// 文件:Program.cs
using System;Console.WriteLine("Hello C# 9!");  // 直接编写主逻辑
return 0;  // 支持返回值 
(4)模式匹配增强(Enhanced Pattern Matching)
  • 作用:扩展isswitch表达式,支持更复杂的类型检查和逻辑组合
// 关系模式 + 逻辑组合
static string CheckTemperature(double temp) => temp switch
{< -10 => "极寒",>= -10 and < 5 => "寒冷",>= 5 and < 25 => "温和",>= 25 => "炎热"
};Console.WriteLine(CheckTemperature(30));  // 输出:"炎热"
(5)目标类型推导的new表达式(Target-typed new)
  • 作用:省略实例化时的重复类型声明
// C# 8
List<string> list1 = new List<string>();// C# 9
List<string> list2 = new();  // 自动推导类型 
Person employee = new() { FirstName = "John" };  // 结合初始化器
(6)with表达式(with Expressions)
  • 作用:基于已有记录创建新实例并修改部分属性
var original = new Book("C# Basics", "TechPub");
var updated = original with { Author = "NewAuthor" };  // 创建副本并修改作者 Console.WriteLine(updated); // 输出:Book { Title = C# Basics, Author = NewAuthor }
(7)协变返回类型(Covariant Return Types)
  • 作用:允许重写方法返回派生程度更大的类型
public class Animal
{public virtual Animal Create() => new Animal();
}public class Dog : Animal
{public override Dog Create() => new Dog();  // 返回更具体的类型 
}
http://www.dtcms.com/a/462605.html

相关文章:

  • 两个RNA-蛋白以及蛋白间相互作用数据库
  • 《低速园区场景下决策模块的成本函数设计与编程实践》
  • 网站推广方法是什么企业网站建设cms系统
  • SpringBoot 集成 LangChain4j 本地调用 Ollama
  • 大前端最新网站设计一个企业官网的栏目
  • Vue 菜单权限管理的计与实现
  • 怎么自己做网站共享办公室 设计
  • Linux进程第八讲——进程状态全景解析(二):从阻塞到消亡的完整生命周期
  • 网站设计审美角度公司手机网站建设
  • 【数据结构】优先级队列(堆)
  • 合肥网站建设首选 晨飞网络nas的wordpress的端口
  • 动漫网站开发优势网店交易哪个平台好
  • Python 中的集合(set)知识大全
  • 网站开发工具的功能包括现在的公司都有自己的网站吗
  • 浏览器访问百度首页的七层协议协作流程
  • 陕西中小企业网站建设推广促销直播网站开发
  • 算起计算器APP发布
  • 做类似淘宝的网站设计需要什么视频素材模板免费下载网
  • 商业网站源码安卓app是用什么语言开发的
  • ros2 自定义消息、服务、动作接口详细范例
  • 企业网站托管后果html5和h5的区别
  • 做网站营业执照经营范围怎么填写如何修改asp网站栏目
  • css里的where选择器的用法
  • 网站人多怎么优化全网引擎搜索
  • 10-七麦js扣代码
  • 做一婚恋网站多少钱医疗网络营销方式
  • golang面经——sync相关
  • wordpress 财经插件wordpress mysql优化
  • 软考中级习题与解答——第十四章_UML建模(5)
  • 万网怎样做网站调试字体怎么装到wordpress