Skip to content

.NET 9 新特性

2024 年 2 月 13 日,.NET 9 发布第一个预览版

下载 .NET 9.0

序列化

在 System.Text.Json 中,.NET 9 提供了用于序列化 JSON 的新选项和新的单一实例,可以更轻松地使用 Web 默认值进行序列化。

  • JsonSerializerOptions 包括新的属性,可支持自定义写入 JSON 的缩进字符和缩进大小。
c#
var options = new JsonSerializerOptions
{
    WriteIndented = true,
    IndentCharacter = '\t',
    IndentSize = 2,
};

LINQ

  • 引入了新的方法 CountByAggregateBy。 借助这些方法,可以按键聚合状态,而无需通过 GroupBy 分配中间分组。借助 CountBy,可以快速计算每个键的频率。
c#
string sourceText = """
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Sed non risus. Suspendisse lectus tortor, dignissim sit amet,
    adipiscing nec, ultricies sed, dolor. Cras elementum ultrices amet diam.
""";

// Find the most frequent word in the text.
KeyValuePair<string, int> mostFrequentWord = sourceText
    .Split(new char[] { ' ', '.', ',' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(word => word.ToLowerInvariant())
    .CountBy(word => word)
    .MaxBy(pair => pair.Value);

Console.WriteLine(mostFrequentWord.Key); // amet

加密

对于加密,.NET 9 在 CryptographicOperations 类型上添加了一个新的一次性哈希方法。 它还添加了使用 KMAC 算法的新类。

  • CryptographicOperations.HashData() 方法
c#
static void HashAndProcessData(HashAlgorithmName hashAlgorithmName, byte[] data)
{
    byte[] hash = CryptographicOperations.HashData(hashAlgorithmName, data);
    ProcessHash(hash);
}
  • KMAC 算法
c#
if (Kmac128.IsSupported)
{
    byte[] key = GetKmacKey();
    byte[] input = GetInputToMac();
    byte[] mac = Kmac128.HashData(key, input, outputLength: 32);
}
else
{
    // Handle scenario where KMAC isn't available.
}

性能

  • 编译器增强
  • 循环优化
  • 本机 AOT 的内联改进
  • .NET 库中的 Arm64 矢量化
你觉得这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度