C#14在.NET 10中的更新
·
nameof在未定泛型(Unbound generic)中的使用
nameof的入参可以是未定泛型(Unbound generic),比如List<>。表达式的结果是List。以前,你需要给泛型指定参数类型。
Console.WriteLine("Hello, World!");
Console.WriteLine("This is a .NET 10.0 application using C# 14.0 features.");
Console.WriteLine($"List<>: {nameof(List<>)}");
Console.WriteLine($"HashSet<>: {nameof(HashSet<>)}");
Console.WriteLine($"Dictionary<,>: {nameof(Dictionary<,>)}");
Console.WriteLine($"Span<>: {nameof(Span<>)}");
Console.WriteLine($"KeyValuePair<,>: {nameof(KeyValuePair<,>)}");
输入结果如下所示。
Hello, World!
This is a .NET 10.0 application using C# 14.0 features.
List<>: List
HashSet<>: HashSet
Dictionary<,>: Dictionary
Span<>: Span
KeyValuePair<,>: KeyValuePair
利用Field增强属性声明
关键字field可以支持你自定义属性的声明。在get或set中使用基于上下文的关键字field,编译器会自动生成对应的代码。你可以自定义get或set的操作方式。比如下列代码。
namespace NET10
{
public class TimePeriod4
{
public double Hours
{
get;
set => field = (value >= 0)
? value
: throw new ArgumentOutOfRangeException(nameof(value), $"The value must not be negative: {value}");
}
}
}
用下列代码引用类TimePeriod4,可获得如下结果。我们在对Hours设置值-3.0的时候,TimePeroid4会自动进行值检查并抛出异常。
var period = new TimePeriod4();
period.Hours = 5.0;
period.Hours = -3.0; // This will throw an ArgumentOutOfRangeException

修饰符ref、in、out可以用在lambda表达式的入参上
你可以在lambda表达式的入参上添加修饰符,比如ref、in、out,而且不需要指定参数类型。
参考文献
1. C# 14 updates in .NET 10 Preview 1 - Release Notes
3. 内置类型 (C# 参考)
更多推荐


所有评论(0)