C#委托和字典的结合使用

目录

 

例1:

例2:


例1:

namespace ConsoleApp9
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<char, Func<float, float, float>> myDictionary = new Dictionary<char, Func<float, float, float>>();
            myDictionary.Add('+', Add);
            myDictionary.Add('-', Substract);
            myDictionary.Add('*', Multiply);
            myDictionary.Add('/', Divide);

            myDictionary['+'](9, 3);
            myDictionary['-'](9, 3);
            myDictionary['*'](9, 3);
            myDictionary['/'](9, 3);

            Console.ReadKey();
        }
        public static float Add(float a, float b)
        {
            float result = a + b;
            Console.WriteLine(a + "+" + b + "的值为:" + result);
            return result ;
        }
        public static float Substract(float a, float b)
        {
            float result = a - b;
            Console.WriteLine(a + "-" + b + "的值为:" + result);
            return result;
        }
        public static float Multiply(float a, float b)
        {
            float result = a * b;
            Console.WriteLine(a + "*" + b + "的值为:" + result);
            return result;
        }
        public static float Divide(float a, float b)
        {
            float result = a / b;
            Console.WriteLine(a + "/" + b + "的值为:" + result);
            return result;
        }
    }
}

例2:

 class Program
    {      
        static void Main(string[] args)
        {
            Dictionary<string, Action<string>> myDictionary = new Dictionary<string, Action<string>>();
            if(!myDictionary.ContainsKey ("姓名"))
            {
                myDictionary["姓名"] = null;
            }
            myDictionary["姓名"] += Test1;
            myDictionary["姓名"] += Test2;
            myDictionary["姓名"] += Test3;
            myDictionary["姓名"]("李疆");

            Console.ReadKey();
        }
        public static void Test1(string name)
        {
            Console.WriteLine("你好,"+name );
        }
        public static void Test2(string name)
        {
            Console.WriteLine("很高兴认识你,"+name );
        }
        public static void Test3(string name)
        {
            Console.WriteLine("拜拜,"+name );
        }
    }

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值