Dictionary of Action Delegates

后端 未结 2 957
滥情空心
滥情空心 2020-12-06 02:29

I have object XML serialized messages coming into a class called MessageRouter. The XML contains the Type name it it was serialized from, a

2条回答
  •  既然无缘
    2020-12-06 02:52

    I am not sure that this completely answers your question, but here is a class I wrote that will accomplish what you want. I couldn't tell if you want your Action delegate to take a typed object or not, but in your pseudo code, you pass it an "object" to deserialize so I wrote my class accordingly and it therefore does not use generics:

    public delegate void Action(object o);
    
    public class DelegateDictionary {
        private IDictionary _dictionary = new Hashtable();
    
        public void Register(Action action) {
            _dictionary[typeof(T)] = action;
        }
    
        public Action Get() {
            return (Action)_dictionary[typeof(T)];
        }
    
        public static void MyFunc(object o) {
            Console.WriteLine(o.ToString());
        }
    
        public static void Run() {
            var dictionary = new DelegateDictionary();
            dictionary.Register(MyFunc);
            // Can be converted to an indexer so that you can use []'s
            var stringDelegate = dictionary.Get();
            stringDelegate("Hello World");
        }
    }
    

    I believe this will accomplish what you want.

提交回复
热议问题