Created
June 27, 2017 05:57
-
-
Save AxelUser/c8d95d492b33ebecc6838627953a449b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace ProITR.Asur.Isur.Coordinate.Handler.Handlers.MessageHandlers | |
{ | |
public class MessageTypeSwitch | |
{ | |
private object _messageToCast; | |
private Dictionary<Type, Action> _mappedActions = new Dictionary<Type, Action>(); | |
public string _couldNotCastErrorMessage { get; set; } | |
public Action<string> _couldNotCastErrorAction { get; set; } | |
public MessageTypeSwitch(object message, string couldNotCastErrorMessage = null) | |
{ | |
_messageToCast = message; | |
} | |
public static MessageTypeSwitch SwitchType(object message, string couldNotCastErrorMessage = null) | |
{ | |
return new MessageTypeSwitch(message, couldNotCastErrorMessage); | |
} | |
public MessageTypeSwitch MapType<T>(Action actionIfCastSuccessful) | |
{ | |
_mappedActions.Add(typeof(T), actionIfCastSuccessful); | |
return this; | |
} | |
public MessageTypeSwitch CatchCouldNotCast(Action<string> actionIfCouldNotCast, | |
string message = "Не удалось привести сообщение из очереди ни к одному из типов") | |
{ | |
_couldNotCastErrorAction = actionIfCouldNotCast; | |
_couldNotCastErrorMessage = message; | |
return this; | |
} | |
public void RunCast() | |
{ | |
foreach (KeyValuePair<Type, Action> mappedAction in _mappedActions) | |
{ | |
Type typeToCast = mappedAction.Key; | |
try | |
{ | |
Convert.ChangeType(_messageToCast, typeToCast); | |
break; | |
} | |
catch | |
{ | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment