delegateとFunc<>

関数ポインタ的なことの覚え書き。

こんな感じ?

    public class CreateCommand
    {
        private delegate string CreateDelegate(int value);

        private readonly Dictionary<string, CreateDelegate> CommandMap
            = new Dictionary<string, CreateDelegate>();

        public CreateCommand()
        {
            this.CommandMap.Add("ボタン", CreateButton);
            this.CommandMap.Add("ライン", CreateLine);
        }

        private string CreateButton(int value)
        {
            return string.Format("button{0:D3}", value);
        }

        private string CreateLine(int value)
        {
            return string.Format("line{0:D3}", value);
        }

        public string Execute(string key, int value)
        {
            return CommandMap[key](value);
        }
    }

    public class TestCommand
    {
        private readonly Dictionary<int, Func<int, int>> TestFunc
            = new Dictionary<int, Func<int, int>>
            {
                {
                    0, (value) => value * 2
                },
                {
                    1, (value) => value / 2
                },
            };

        public string Execute(int key, int value)
        {
            return TestFunc[key](value);
        }

    }