Словарь действий <T> делегатов
У меня есть объектXML serialized messages входить в класс под названиемMessageRouter, XML содержит имя типа, с которого оно было сериализовано, и мне нужно иметь возможностьinvoke different delegate methods depending on the type that are not known until runtime, Я не очень силен в дженериках, так что, надеюсь, это кому-нибудь пригодится ...
Я хотел бы, чтобы MessageRouter предоставилRegisterDelegateForType метод вроде так:
myMessageRouter.RegisterDelegateForType(new Action<MySerializableType>(myActionHandler));
А затем сохраните типы или строковое представление типа в Словаре, например:
Dictionary<Type, Action<T>> registeredDelegates;
Таким образом, я могу сделать что-то вроде следующего псевдокода, вызывая назначенный делегат типа и передавая десериализованный объект:
Type xmlSerializedType = TypeFromXmlString(incomingXml);
object deserializedObject = DeserializeObjectFromXml(xmlSerializedType, incomingXml);
// then invoke the action and pass in the deserialized object
registeredDelegates[xmlSerializedType](deserializedObject);
Итак, мои вопросы:
How do you define a Dictionary that can contain aType
as a key and a generic Action<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?