C# Func的用法

C#中Fun和前面介绍过的Action有点类似,都是一个委托方法

不同的是Func是有返回值的,而Action没有

Fun常用有两个参数,前面的是输入参数,后面的是输出参数(意味着是在另一部分运算中产生的)恰恰是整个方法的返回值

(T arg)代表的是和输出参数类型相同的方法名称(返回值的类型和Func输出参数类型相同)

Fnc最多有16个输入参数,有且只有一个输出参数

Func<TResult> function代表function函数的返回值得类型是TResult。


//
    // 摘要:
    //     Encapsulates a method that has one parameter and returns a value of the type
    //     specified by the TResult parameter.To browse the .NET Framework source code for
    //     this type, see the Reference Source.
    //
    // 参数:
    //   arg:
    //     The parameter of the method that this delegate encapsulates.
    //
    // 类型参数:
    //   T:
    //     The type of the parameter of the method that this delegate encapsulates.This
    //     type parameter is contravariant. That is, you can use either the type you specified
    //     or any type that is less derived. For more information about covariance and contravariance,
    //     see Covariance and Contravariance in Generics.
    //
    //   TResult:
    //     The type of the return value of the method that this delegate encapsulates.This
    //     type parameter is covariant. That is, you can use either the type you specified
    //     or any type that is more derived. For more information about covariance and contravariance,
    //     see Covariance and Contravariance in Generics.
    //
    // 返回结果:
    //     The return value of the method that this delegate encapsulates.
    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
    public delegate TResult Func<in T, out TResult>(T arg);


         public void Test()
        {
            //1.
            Func<string, int> func1 = MyMethodA;
            Console.WriteLine(func1("feige"));

            //2.
            MyMethodB<string>(new Func<string, int>(MyMethodA), "feige");

            //3
            MyMethodB(new Func<string, int>(MyMethodA), "feige");
        }

        public int MyMethodA(string str)
        {
            if (string.IsNullOrEmpty(str))
                return 0;
            return 1;
        }

        public void MyMethodB<T>(Func<T, int> func, T t)
        {
            Console.WriteLine(func(t));
        }




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值