下面代碼中的 MakeGenericMethod 拋出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 });
}
}
}
請注意,CityList 擴展了 PagedResults,其中 City 擴展了 MyDTO
我做錯了什么來獲得例外?
謝謝
uj5u.com熱心網友回復:
該方法的通用引數是TResult,而MakeGenericMethod代碼中使用的引數是繼承自PagedResults<TResult>
嘗試這樣的事情:
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 });
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/496134.html
