Skip to content

Instantly share code, notes, and snippets.

@AxelUser
Created June 27, 2017 05:57
Show Gist options
  • Save AxelUser/c8d95d492b33ebecc6838627953a449b to your computer and use it in GitHub Desktop.
Save AxelUser/c8d95d492b33ebecc6838627953a449b to your computer and use it in GitHub Desktop.
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