C# MakeGenericMethod抛出TResult约束违反VerificationException问题
错误原因
异常触发的核心原因是传入MakeGenericMethod的泛型参数不符合方法的泛型约束:
Calculate<TResult>方法定义的泛型参数TResult有继承MyDTO的约束,且方法入参为PagedResults<TResult>,说明TResult是分页结果集中的元素类型,而非分页容器本身的类型。- 现有代码直接将
objectResult.Value.GetType()作为泛型参数传入,该类型是自定义分页类CityList——CityList的定义是class CityList : PagedResults<City>,属于分页容器类型,本身并未继承MyDTO,完全不满足TResult的约束要求,因此抛出VerificationException。 - 附带问题:原代码的类型判断逻辑存在两处缺陷:一是
IsAssignableFrom调用方向错误,二是直接取BaseType无法兼容多层继承的分页类场景,会漏判合法的分页结果类型。
修复方案
不要直接传入分页对象的类型,先从分页对象的类型链路中找到PagedResults<>泛型定义对应的泛型实参(也就是元素类型City),再将该元素类型传入MakeGenericMethod即可。
修复后的核心代码如下:
public override void OnActionExecuted(ActionExecutedContext context) { var valueInstance = objectResult.Value; var currentType = valueInstance.GetType(); Type pagedResultGenericType = null; // 向上递归查找类型链路,找到PagedResults<>的泛型实例类型 while (currentType != null) { if (currentType.IsGenericType && currentType.GetGenericTypeDefinition() == typeof(PagedResults<>)) { pagedResultGenericType = currentType; break; } currentType = currentType.BaseType; } if (pagedResultGenericType != null) { MethodInfo calculateMethod = GetType().GetMethods().Single(m => m.Name == "Calculate"); // 提取PagedResults<T>中的T(元素类型)作为泛型参数 var elementType = pagedResultGenericType.GetGenericArguments()[0]; var genericCalculate = calculateMethod.MakeGenericMethod(elementType); genericCalculate.Invoke(this, new[] { valueInstance }); } }
修复后传入的泛型参数是City类型,该类型继承自MyDTO,完全符合泛型约束,调用可正常执行。
内容的提问来源于stack exchange,提问作者watchloop
相关产品推荐
相关产品推荐

