MakeGenericMethod in the below code throws VerificationException: Method MyClass.Calculate: type argument CityList'violates the constraint of type parameter 'TResult'
public class MyCustomActionFilterAttribute : ActionFilterAttribute
{
public void Calculate<TResult>(PagedResults<TResult> pagedResults) where TResult : MyDTO
{
foreach (TResult dto in pagedResults.Value)
{
//Do something to dto
}
}
/// <inheritdoc />
public override void OnActionExecuted(ActionExecutedContext context)
{
if (objectResult.Value.GetType().BaseType.GetGenericTypeDefinition().IsAssignableFrom(typeof(PagedResults<>)))
{
MethodInfo calculateMethod = this.GetType().GetMethods().Single(m => m.Name == "Calculate");
calculateMethod = calculateMethod.MakeGenericMethod(objectResult.Value.GetType());
calculateMethod.Invoke(this, new object[] { objectResult.Value });
}
}
}
Please note that CityList extends PagedResults where City extends MyDTO
What am I doing wrong to get the exception?
Thanks
CodePudding user response:
The method's generic argument is TResult
whereas the parameter used with MakeGenericMethod
in your code is inhertied from PagedResults<TResult>
Try something like this:
Type FindGenericResultType(object pagedResults)
{
var type = pagedResults.GetType();
while (type != null)
{
if (type.IsGenericType && typeof(PagedResults<>).IsAssignableFrom(type.GetGenericTypeDefinition())
{
return type.GetGenericArguments()[0];
}
type = type.BaseType;
}
return null;
}
var resultType = FindGenericResultType(objectResult.Value);
if (resultType != null)
{
MethodInfo calculateMethod = this.GetType().GetMethods().Single(m => m.Name == "Calculate");
calculateMethod = calculateMethod.MakeGenericMethod(resultType);
calculateMethod.Invoke(this, new object[] { objectResult.Value });
}