委托实例(控制台)

using System;

namespace Test
{
    class TransientTest
    {

        delegate void Student(string s); //声明委托

        delegate int del(int i);  //声明委托

        delegate T Func<X, T>(X x);  //声明泛型委托:T是返回值类型,X是参数类型

        static void M(string s)
        {
            Console.WriteLine(s);
        }

        static void Main(string[] args)
        {
            Student sd = new Student(M);  //将M方法委托sd
            sd("Hello!");

            Student sd1 = delegate (string s) { Console.WriteLine(s); };  //匿名委托
            sd1("Hello!!");

            Student sd2 = (s) => { Console.WriteLine(s); };  //Lambda表达式委托
            sd2("Hello!!!");

            del Del = x => x * x;  //Lambda表达式委托
            Console.WriteLine(Del(5));  

            Func<int, bool> func = x => x > 0;  //泛型委托
            Console.WriteLine(func(4));

            Console.ReadLine();
        }
    }
}

简单的介绍

猜你喜欢

转载自blog.csdn.net/qq_39081464/article/details/81130363