class FixedArgumentValidationAsyncLambda
{
static void Main()//使用异步匿名函数进行参数验证
{
MainAsync().Wait();
}
static async Task MainAsync()
{
Task<int> task = ComputeLengthAsync(null);
// We never get this far, as the exception is thrown eagerly.
Console.WriteLine("Fetched the task");
int length = await task;
Console.WriteLine("Length: {0}", length);
}
static Task<int> ComputeLengthAsync(string text)
//text null
{
if (text == null)//执行这句 完全异步验证
{
throw new ArgumentNullException("text");//回主函数
}
Func<Task<int>> func = async () => //创建一个异步函数
{
await Task.Delay(500); // 模拟真正异步工作
return text.Length;
};
return func(); //调用匿名函数
}
}
深入理解 c# 第十五章 使用异步匿名函数进行参数验证 异步匿名函数
最新推荐文章于 2026-05-24 08:42:59 发布
本文探讨了如何在C#中使用异步匿名函数进行参数验证。虽然这不是一个真正的异步方法,但通过这种方式可以保持代码的清晰性。然而,这种方法可能会带来性能损失,因为额外的包装会产生开销。在性能敏感的场景下,需要实际测试成本以决定最佳实践。


3332

被折叠的 条评论
为什么被折叠?



