Func的介绍

原型

Func是一个.Net内置的委托。

命名空间 System

Assemblies: System.Runtime.dll, mscorlib.dll, netstandard.dll, System.Core.dll

使用版本:
.NET Core
2.1 2.0 1.1 1.0
.NET Framework
4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 4.5.2 4.5.1 4.5 4.0 3.5
.NET Standard
2.0 1.6 1.5 1.4 1.3 1.2 1.1 1.0
Xamarin.Android
7.1
Xamarin.iOS
10.8
Xamarin.Mac
3.0

 

其原型说明如下:

 // 摘要:
    //     封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
    //
    // 参数:
    //   arg:
    //     此委托封装的方法的参数。
    //
    // 类型参数:
    //   T:
    //     此委托封装的方法的参数类型。
    //
    //   TResult:
    //     此委托封装的方法的返回值类型。
    //
    // 返回结果:
    //     此委托封装的方法的返回值。
    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
    public delegate TResult Func<in T, out TResult>(T arg);

in T 代表输入参数                     1
out TResult 表示输出参数          2
再看返回值是 TResult                3
构造方法需要的参数是T               4

使用范例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int, bool> f1 = IsNumberLessThen5;
            bool flag = f1(4);
            Console.WriteLine(flag);

            //以下是其它的用法,与IsNumberLessThen5作用相同。只是写法不同而已。
            Func<int, bool> f2 = i => i < 5;
            Func<int, bool> f3 = (i) => { return i < 5; };
            Func<int, bool> f4 = delegate(int i) { return i < 5; };
            flag = f2(4); Console.WriteLine(flag);
            flag = f3(4); Console.WriteLine(flag);
            flag = f4(4); Console.WriteLine(flag);            

            Console.ReadLine();
        }

        private static bool IsNumberLessThen5(int number)
        {
            if (number < 5)
                return true;
            return false;
        }
    }
}

在 C# 中将 Func<T, TResult> 委托与匿名方法一起使用。

1 using System;
 2 
 3 public class Anonymous
 4 {
 5    public static void Main()
 6    {
 7       Func<string, string> convert = delegate(string s)
 8          { return s.ToUpper();}; 
 9 
10       string name = "Dakota";
11       Console.WriteLine(convert(name));   
12    }
13 }

将 lambda 表达式分配给 Func<T, TResult> 委托。

 1 using System;
 2 
 3 public class LambdaExpression
 4 {
 5    public static void Main()
 6    {
 7       Func<string, string> convert = s => s.ToUpper();
 8 
 9       string name = "Dakota";
10       Console.WriteLine(convert(name));   
11    }
12 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mystonelxj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值