委托之Action与Func

1 例程代码:

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

namespace 委托之Action与Func
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("【1】演示Action 委托:");
            var actDele = new Action(TestMethods.SelfIntroduce);
            actDele += TestMethods.SayHi;
            actDele.Invoke();//调用委托

            ShowTool.PrintDelimiter(50);
            Console.WriteLine("【2.1】演示Func<int,int,int>委托:");
            var func1 = new Func<int, int, int>(TestMethods.Add2Num);
            Console.WriteLine("请输入第一个数:");
            int a = ShowTool.GetNumInit();
            Console.WriteLine("请输入第二个数:");
            int b = ShowTool.GetNumInit();
            Console.WriteLine(func1.Invoke(a, b));

            ShowTool.PrintDelimiter(50);
            Console.WriteLine("【2.2】演示Func<double,double,double>委托:");
            var func2 = new Func<double,double,double>(TestMethods.Multiple2Num);
            Console.WriteLine("请输入第一个数:");
            double x = ShowTool.GetNumDouble();
            Console.WriteLine("请输入第二个数:");
            double y = ShowTool.GetNumDouble();
            Console.WriteLine(func2.Invoke(x, y)); 
            Console.ReadKey();

        }
    }
    class TestMethods
    {
        internal static void SayHi()
        {
            Console.WriteLine("Hello,Dell Mao");
        }
        public static void SelfIntroduce()
        {
            Console.WriteLine("Hi,My name is Dell Mao!");
        }
        public static int Add2Num(int a, int b)
        {
            return a + b;
        }

        public static double Multiple2Num(double a, double b)
        {
            return a * b;
        }
    }
    class ShowTool
    {
        public static void PrintDelimiter(int lenght)//打印一个分隔符
        {
            if (lenght < 8)
            {
                lenght = 8;
            }
            for (int i = 0; i < lenght; i++)
            {
                Console.Write("=");
            }
            Console.WriteLine();
        }
        public static int GetNumInit()
        {
            int a = 0;
            try
            {
                a = Convert.ToInt32(Console.ReadLine());
                return a;
            }
            catch (Exception)
            {
                MessageBox.Show("您输入的数据格式有误,将使用默认值0。");
                return a;
            }
        }
        public static double GetNumDouble()
        {
            double a = 0;
            try
            {
                a = Convert.ToDouble(Console.ReadLine());
                return a;
            }
            catch (Exception)
            {
                MessageBox.Show("您输入的数据格式有误,将使用默认值-999。");
                return a;
            }
        }
    }
}

 2 运行结果:

Action与Function委托例子运行结果

posted @ 2023-11-22 23:11  Stephen_Young  阅读(21)  评论(0编辑  收藏  举报