Skip to content

Commit

Permalink
Fix support for target object events with certain generic delegates
Browse files Browse the repository at this point in the history
When the delegate's generic type argument is not used directly as the 2nd parameter type in the event handler delegate, a NotSupportedException was thrown starting with pull request microsoft#285.

Fixes microsoft#292
  • Loading branch information
AArnott committed Jun 20, 2019
1 parent 3546527 commit e8ab5da
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/StreamJsonRpc/JsonRpc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2007,14 +2007,20 @@ internal EventReceiver(JsonRpc jsonRpc, object server, EventInfo eventInfo, Json
// It will work for EventHandler and EventHandler<T>, at least.
// If we want to support more, we'll likely have to use lightweight code-gen to generate a method
// with the right signature.
if (eventInfo.EventHandlerType.Equals(typeof(EventHandler)))
var eventHandlerParameters = eventInfo.EventHandlerType.GetTypeInfo().GetMethod("Invoke").GetParameters();
if (eventHandlerParameters.Length != 2)
{
throw new NotSupportedException($"Unsupported event handler type for: \"{eventInfo.Name}\". Expected 2 parameters but had {eventHandlerParameters.Length}.");
}

Type argsType = eventHandlerParameters[1].ParameterType;
if (typeof(EventArgs).GetTypeInfo().IsAssignableFrom(argsType))
{
this.registeredHandler = OnEventRaisedMethodInfo.CreateDelegate(eventInfo.EventHandlerType, this);
}
else
{
Type eventArgsType = eventInfo.EventHandlerType.GenericTypeArguments.FirstOrDefault() ?? typeof(object);
var closedGenericMethod = OnEventRaisedGenericMethodInfo.MakeGenericMethod(eventArgsType);
var closedGenericMethod = OnEventRaisedGenericMethodInfo.MakeGenericMethod(argsType);
this.registeredHandler = closedGenericMethod.CreateDelegate(eventInfo.EventHandlerType, this);
}
}
Expand Down

0 comments on commit e8ab5da

Please sign in to comment.