C# Func简记


Func<[类型1],[类型2],...[类型n]> 方法名([参数1],[参数2]...) = (p1,p1...) =>{/** 方法**/ return 返回值;}

Action 类似Func,区别在于没有返回类型

### C# 中 `Func` 的定义与用途 `Func<T>` 是一种通用委托类型,用于表示具有指定参数并返回特定类型的函数[^1]。它允许开发者通过简洁的方式传递方法作为参数或将方法存储在变量中。 #### 特性描述 - **泛型支持**:`Func` 支持多种输入参数以及单一的返回值。 - **灵活性高**:可以用来简化 Lambda 表达式的使用场景。 - **内置实现**:无需显式声明自定义委托即可完成常见操作。 以下是不同版本的 `Func` 定义及其适用范围: | 泛型数量 | 参数说明 | |----------|------------------------------| | `Func<TResult>` | 不带任何参数,仅返回 TResult 类型的结果 | | `Func<T, TResult>` | 接受 T 类型参数,返回 TResult 结果 | | `Func<T1,T2,TResult>`| 接受两个参数 (T1 和 T2),返回 TResult | #### 使用示例 下面是一些常见的 `Func` 实现方式的例子: ```csharp // Example of using Func with no parameters but returning a value. Func<int> getRandomNumber = () => new Random().Next(10); Console.WriteLine(getRandomNumber()); // Example where the function accepts one parameter and returns an int result. Func<int, int> multiplyByTwo = number => number * 2; Console.WriteLine(multiplyByTwo(5)); // A more complex example involving multiple input arguments. Func<int, string, bool> checkIfAgeMatchesNameLength = (age, name) => age == name.Length; bool isMatched = checkIfAgeMatchesNameLength(7, "Edward"); Console.WriteLine(isMatched); // Outputs true or false based on condition match ``` 上述代码展示了如何利用 `Func` 来创建匿名方法或者 lambda 函数来处理数据转换、验证逻辑等问题。 #### 总结 `Func` 提供了一种强大而灵活的方式来封装可执行代码片段,并且能够轻松集成到 LINQ 查询以及其他高级特性当中去。这使得程序设计更加模块化和易于维护。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值