/// <summary>
/// Remove all the eventhandlers from StateChanged event of original store (<see cref="_store"/>), and return them
/// as a combined multi cast delegate.
/// <a href="https://stackoverflow.com/a/16089998/605113">Reference</a>
/// </summary>
/// <param name="originalStore"></param>
/// <returns>Combined Delegate of StateChanged event handlers attached to original store.</returns>
private Delegate ShiftAllEvents(IStore <TState> originalStore)
{
// @ref: https://stackoverflow.com/a/16089998/605113
Type theType = originalStore.GetType();
Delegate finalDelegate = null;
//Even though the events are public, the FieldInfo associated with them is private
foreach (System.Reflection.FieldInfo field in theType.GetTypeInfo().DeclaredFields)
{
//eventInfo will be null if this is a normal field and not an event.
System.Reflection.EventInfo eventInfo = theType.GetTypeInfo().GetDeclaredEvent(field.Name);
if (eventInfo != null && field.Name == nameof(StateChanged))
{
MulticastDelegate multicastDelegate = field.GetValue(originalStore) as MulticastDelegate;
if (multicastDelegate != null)
{
List <Delegate> oldHandlers = new List <Delegate>();
foreach (Delegate @delegate in multicastDelegate.GetInvocationList())
{
eventInfo.RemoveEventHandler(originalStore, @delegate);
oldHandlers.Add(@delegate);
}
if (oldHandlers.Count > 0)
{
finalDelegate = Delegate.Combine(oldHandlers.ToArray());
}
}
}
}
return(finalDelegate);
}