码迷,mamicode.com
首页 > 其他好文 > 详细

数据字典+匿名委托模拟switch/case功能

时间:2015-09-13 23:12:50      阅读:502      评论:0      收藏:0      [点我收藏+]

标签:

基本思想每个case的选择值作为键,处理过程做成函数委托存放进数据字典。用的时候根据之调用。下面上代码


封装的FuncSwitcher类

using System;
using System.Collections.Generic;

namespace Test
{
    class FuncSwitcher<T>
    {
        int count;
        Dictionary<T, Delegate> FuncGather;
        Delegate defalutFunc;
        public FuncSwitcher()
        {
            count = 0;
            FuncGather = new Dictionary<T, Delegate>();
        }
        /// <summary>
        /// 调用函数处理
        /// </summary>
        /// <param name="t"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public object Invoke(T t, object[] parameters)
        {
            if (FuncGather.ContainsKey(t))
            {
                var method = FuncGather[t];
                return method.Method.Invoke(method, parameters);
            }
            else
            {
                var method = defalutFunc;
                return method.Method.Invoke(method, null);
            }
        }
        /// <summary>
        /// 添加默认处理函数
        /// </summary>
        /// <param name="defaultFunc"></param>
        public void AddDefault(Delegate defaultFunc)
        {
            this.defalutFunc = defaultFunc;
        }
        /// <summary>
        /// 添加键值对
        /// </summary>
        /// <param name="key"></param>
        /// <param name="func"></param>
        public void AddFunc(T key, Delegate func)
        {
            FuncGather.Add(key, func);
        }
        /// <summary>
        /// 添加多对键值
        /// </summary>
        /// <param name="funcs"></param>
        public void AddRange(KeyValuePair<T, Delegate>[] funcs)
        {
            foreach (KeyValuePair<T, Delegate> func in funcs)
            {
                FuncGather.Add(func.Key, func.Value);
            }
        }
        /// <summary>
        /// 移除键值对
        /// </summary>
        /// <param name="t"></param>
        public void Remove(T t)
        {
            FuncGather.Remove(t);
        }
        /// <summary>
        /// 获取函数
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public Delegate GetFunc(T t)
        {
            return FuncGather[t];
        }
        /// <summary>
        /// 是否包含键
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool ContainKey(T t)
        {
            if (FuncGather.ContainsKey(t))
                return true;
            else
                return false;
        }
        /// <summary>
        /// 是否包含值
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool ContainValue(Delegate t)
        {
            if (FuncGather.ContainsValue(t))
                return true;
            else
                return false;
        }
        /// <summary>
        /// 清空键值
        /// </summary>
        public void Clear()
        {
            FuncGather.Clear();
            count = 0;
        }
        public int Count
        {
            get { return count; }
        }
    }
}

测试用的函数,我最偏好的加减乘除,用什么其实都无所谓。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Configuration;
using System.Diagnostics;
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            FuncSwitcher<ConsoleKey> Switcher = new FuncSwitcher<ConsoleKey>();
            ConsoleKeyInfo flag;
            Switcher.AddFunc(ConsoleKey.D0, new Action(() => { SwitchTest(); }));
            Switcher.AddFunc(ConsoleKey.D1, new Action(() => { CustomSwitchTest(); }));
            Switcher.AddFunc(ConsoleKey.D2, new Action(() => { Console.WriteLine("程序已经退出"); Environment.Exit(0); }));
            Switcher.AddDefault(new Action(() => { Console.WriteLine("重新输入"); }));

            while (true)
            {
                Console.WriteLine("********************************");
                Console.WriteLine("*****  0:switch测试      ******");
                Console.WriteLine("*****  1: CustomSwitchTest******");
                Console.WriteLine("*****  2: 退出程序        ******");
                Console.WriteLine("********************************");

                flag = Console.ReadKey();
                Console.WriteLine();
                Switcher.Invoke(flag.Key, null);
            }
        }
        /// <summary>
        /// switch/case
        /// </summary>
        public static void SwitchTest()
        {
            Console.WriteLine("********************");
            Console.WriteLine("***** add:加   ****");
            Console.WriteLine("***** sub: 减   ****");
            Console.WriteLine("***** mul: 乘   ****");
            Console.WriteLine("***** div: 除   ****");
            Console.WriteLine("*****   0:返回 ****");
            Console.WriteLine("********************");
            Console.WriteLine("输入操作");
            string operate = Console.ReadLine();
            switch (operate)
            {
                case "add":
                    Console.WriteLine(Add(1, 1));
                    break;
                case "sub":
                    Console.WriteLine(Sub(1, 1));
                    break;
                case "mul":
                    Console.WriteLine(Mul(1, 1));
                    break;
                case "div":
                    Console.WriteLine(Div(1, 1));
                    break;
                default:
                    Console.WriteLine("重新输入");
                    break;
            }
        }
        /// <summary>
        /// 自定义的选择
        /// </summary>
        public static void CustomSwitchTest()
        {
            FuncSwitcher<string> switcher = new FuncSwitcher<string>();
            switcher.AddDefault(new Action(() => { Console.WriteLine("重新输入"); }));
            switcher.AddRange(new KeyValuePair<string, Delegate>[]
            {
               new KeyValuePair<string,Delegate>("add", new Func<int,int,int>(Add)),
               new KeyValuePair<string,Delegate>("sub", new Func<int,int,int>(Sub)),
               new KeyValuePair<string,Delegate>("mul", new Func<int,int,int>(Mul)),
               new KeyValuePair<string, Delegate>("div", new Func<int, int, int>(Div)),
           });

            Console.WriteLine("********************");
            Console.WriteLine("***** add:加   ****");
            Console.WriteLine("***** sub: 减   ****");
            Console.WriteLine("***** mul: 乘   ****");
            Console.WriteLine("***** div: 除   ****");
            Console.WriteLine("*****   0:返回 ****");
            Console.WriteLine("********************");
            Console.WriteLine("输入操作");
            string operate = Console.ReadLine();
            Console.WriteLine(switcher.Invoke(operate, new object[] { 1, 1 }));
        }
        /// <summary>
        /// 测试所用,无所谓了,什么函数都可以的
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public static int Add(int x, int y)
        {
            return x + y;
        }
        public static int Sub(int x, int y)
        {
            return x - y;
        }
        public static int Mul(int x, int y)
        {
            return x * y;
        }
        public static int Div(int x, int y)
        {
            if (y != 0)
                return x / y;
            else throw new DivideByZeroException("除数不可以为0");
        }
    }
}


数据字典+匿名委托模拟switch/case功能

标签:

原文地址:http://my.oschina.net/hunjixin/blog/505665

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!