Tipo de delegado incorporado Csharp

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp内置泛型委托和Lambda表达式
{
    /*
     * 作者:Ai
     * 时间:2018年3月1日23:04:19
     * 
     * C#为我们准备一系列泛型委托模板
     * 使用内置的模板能为我们节省不少时间
     */
    class Program
    {
        static void Main(string[] args)
        {

            //1.Predicate<T>泛型委托
            //Predicate<T>只能传入一个泛型参数,且返回值为bool
            Predicate<string> predicate = new Predicate<string>(Fun_Predicate_String);
            Console.WriteLine(predicate("s"));

            //2.Action泛型委托
            //可以有0-16个参数,但返回值类型必须为Void
            var action = new Action<string, int>(Fun_Action);//var关键字可以省去书写变量类型
            action("AI", 9);

            //3.Func泛型委托
            //形参列表的最后一个类型为返回值类型
            var func = new Func<int, int, int>(Fun_Func);
            Console.WriteLine("较大数为:"+func(10,20));

            //4.委托中的匿名方法
            //可以把代码块传给一个对象
            //可以范围上下中的变量
            int s = 100;
            var ddd = new Predicate<int>(delegate (int i)
            {
                Console.WriteLine("调用匿名方法咯,输入为{0}", i);
                Console.WriteLine("s={0}", s);
                return false;
            });
            ddd(3);




        }


        //方法
        /// <summary>
        /// 判断一个字符串是否为空
        /// </summary>
        /// <param name="str">待匹配的字符串</param>
        /// <returns>True/False</returns>
        static bool Fun_Predicate_String(string str)
        {
            if (str.Equals(""))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 2个参数的泛型方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="K"></typeparam>
        /// <param name="t"></param>
        /// <param name="k"></param>
        static void Fun_Action<T, K>(T t, K k ) where T:class where K: struct
        {
            if (t is string &&k is int)
            {
                Console.WriteLine("姓名为:{0}  年龄为:{1}",t,k);
            }
        }

        /// <summary>
        /// 返回2个整数中的较大数
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        static int Fun_Func(int a,int b)
        {

            return a > b ? a : b;                      
        }
    }
}

25 artículos originales publicados · Me gusta6 · Visitas 10,000+

Supongo que te gusta

Origin blog.csdn.net/qq_37446649/article/details/80445666
Recomendado
Clasificación