I have object XML serialized messages coming into a class called MessageRouter. The XML contains the Type name it it was serialized from, and I need to be able to invoke different delegate methods depending on the type that are not known until runtime. I'm not extremely strong in generics so hopefully this will make sense to someone...
I'd like MessageRouter to provide a RegisterDelegateForType method like so:
myMessageRouter.RegisterDelegateForType(new Action<MySerializableType>(myActionHandler));
And then store the types, or the type's string representation in a Dictionary like this:
Dictionary<Type, Action<T>> registeredDelegates;
That way, I can do something like the following pseudocode, calling the type's assigned delegate and passing the deserialized object:
Type xmlSerializedType = TypeFromXmlString(incomingXml);
object deserializedObject = DeserializeObjectFromXml(xmlSerializedType, incomingXml);
// then invoke the action and pass in the deserialized object
registeredDelegates[xmlSerializedType](deserializedObject);
So my questions are:
- How do you define a Dictionary that can contain a
Type
as a key and a genericAction<T>
as a value, and have the RegisterDelegateForType method populate the dictionary? - If that's not possible, what's the best way to do this?