1. 程式人生 > 實用技巧 >C#新特性

C#新特性

Ref 區域性變數和返回結果

允許使用並返回對變數的引用的演算法,這些變數在其他位置定義。新增 ref 區域性變數和 ref 返回結果可通過避免複製值或多次執行取消引用操作,允許更為高效的演算法。

public static ref int Find(int[,] matrix, Func<int, bool> predicate)
{
    for (int i = 0; i < matrix.GetLength(0); i++)
        for (int j = 0; j < matrix.GetLength(1); j++)
            if (predicate(matrix[i, j]))
                
return ref matrix[i, j]; throw new InvalidOperationException("Not found"); } ref var item = ref MatrixSearch.Find(matrix, (val) => val == 42); Console.WriteLine(item); item = 24; Console.WriteLine(matrix[4, 2]);

表示式體

成員函式、只讀屬性、建構函式、getset訪問器。

// Expression-bodied constructor
public ExpressionMembersExample(string
label) => this.Label = label; private string label; // Expression-bodied get / set accessors. public string Label { get => label; set => this.label = value ?? "Default label"; }

throw表示式

throw可以用作表示式和語句。這允許在以前不支援的上下文中引發異常。這些方法包括條件表示式、null 合併表示式和一些 lambda 表示式。

string arg = args.Length >= 1
? args[0] : throw new ArgumentException("You must supply an argument"); name = value ?? throw new ArgumentNullException(paramName: nameof(value), message: "Name cannot be null"); DateTime ToDateTime(IFormatProvider provider) => throw new InvalidCastException("Conversion to a DateTime is not supported.");

ValueTask

從非同步方法返回Task物件可能在某些路徑中導致效能瓶頸。Task是引用型別,因此使用它意味著分配物件。

ValueTask此增強功能對於庫作者最有用,可避免在效能關鍵型程式碼中分配Task

需要新增 NuGet 包System.Threading.Tasks.Extensions才能使用ValueTask<TResult>型別。

數字文字語法改進

二進位制文字和數字分隔符

public const int OneHundredTwentyEight = 0b1000_0000;

public const long BillionsAndBillions = 100_000_000_000;

public const double AvogadroConstant = 6.022_140_857_747_474e23;

預設文字表示式

針對預設值表示式的一項增強功能。這些表示式將變數初始化為預設值。過去會這麼編寫:

Func<string, bool> whereClause = default(Func<string, bool>);

現在,可以省略掉初始化右側的型別:

Func<string, bool> whereClause = default;