C#基础16-C#6-C#9新特性
1、C#6新特性
(1)表达式属性(Expression-bodied Properties)
作用:简化只读属性的定义,用Lambda语法替代传统get访问器。
public string FullName { get { return $" { FirstName } { LastName } " ; }
}
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) ;
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 ;
string address = order?. Customer?. Address;
(5)异常过滤器(Exception Filters)
作用:根据条件决定是否捕获异常,不满足条件时异常继续向上传递。
try { File. ReadAllText ( "missing.txt" ) ;
}
catch ( IOException ex) when ( ex. Message. Contains ( "not found" ) ) { Console. WriteLine ( "文件未找到,记录日志" ) ;
}
(6)索引初始化器(Index Initializers)
var dict1 = new Dictionary< int , string > ( ) ;
dict1. Add ( 1 , "One" ) ;
dict1. Add ( 2 , "Two" ) ;
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) ) ;
}
(8)静态导入(using static
)
using static System. Math ;
double radius = 10 ;
double area = PI * Pow ( radius, 2 ) ;
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)
作用:通过is
和switch
增强类型检查与条件分支。
object obj = - 10 ;
switch ( obj) { case int i when i > 0 : Console. WriteLine ( $"正数: { i } " ) ; break ; case string s: Console. WriteLine ( $"字符串: { s } " ) ; break ; case null : Console. 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 ;
(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] } " ) ;
Range middle = 3 .. ^ 2 ;
var subset = numbers[ middle] ;
Console. WriteLine ( $"子集: { string . Join ( "," , subset) } " ) ;
string text = "Hello World" ;
Console. WriteLine ( text[ 6 .. ] ) ;
(4)接口默认方法(Default Interface Members)
public interface ILogger
{ void Log ( string message) => Console. WriteLine ( message) ; void LogError ( string error) ;
} public class FileLogger : ILogger
{ public 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 } " ) ;
}
(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 => .. . , _ => throw new ArgumentException ( "未知形状" )
} ;
(8)目标类型new表达式(Target-typed new)
Dictionary< string , int > dict = new Dictionary< string , int > ( ) ;
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" } ;
(2)记录类型(Record Types)
作用:创建不可变数据类型,自动实现值相等性检查和拷贝逻辑
public record Book ( string Title, string Author) ;
var book1 = new Book ( "C# Guide" , "Microsoft" ) ;
var book2 = book1 with { Title = "Advanced C#" } ;
Console. WriteLine ( book1 == book2) ;
(3)顶级语句(Top-level Programs)
作用:简化控制台程序入口,无需显式定义Main
方法
using System ; Console. WriteLine ( "Hello C# 9!" ) ;
return 0 ;
(4)模式匹配增强(Enhanced Pattern Matching)
作用:扩展is
和switch
表达式,支持更复杂的类型检查和逻辑组合
static string CheckTemperature ( double temp) => temp switch
{ < - 10 => "极寒" , >= - 10 and < 5 => "寒冷" , >= 5 and < 25 => "温和" , >= 25 => "炎热"
} ; Console. WriteLine ( CheckTemperature ( 30 ) ) ;
(5)目标类型推导的new
表达式(Target-typed new)
List< string > list1 = new List< string > ( ) ;
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) ;
(7)协变返回类型(Covariant Return Types)
public class Animal
{ public virtual Animal Create ( ) => new Animal ( ) ;
} public class Dog : Animal
{ public override Dog Create ( ) => new Dog ( ) ;
}