我有一个通用类中的通用方法。在这个方法内部,如果该方法的泛型参数类型未映射,但其父类型映射了,则需要调用相同的父类型方法。然而,对于这两段代码,我得到了不同的结果,尽管我希望它们是相同的。
这个成功:
MethodInfo methodInfo2 = this.GetType().GetMethods()[9]; // this is the correct one.
methodInfo2 = methodInfo2.MakeGenericMethod(mappedType);
这会导致崩溃:
MethodInfo methodInfo1 = System.Reflection.MethodBase.GetCurrentMethod() as MethodInfo;
methodInfo1 = methodInfo1.MakeGenericMethod(mappedType);
除此之外:
GenericArguments[0], 'GenericClassConstraintAbstract.Abstract', on 'System.Collections.Generic.IList`1[Entity] GetEntities[Entity](System.Linq.Expressions.Expression`1[System.Func`2[Entity,System.Boolean]], Sbu.Sbro.Common.Core.Pagination.Paginator`1[Entity])' violates the constraint of type 'Entity'.
如果我在调试器监视中添加
methodInfo1 == methodInfo2
,我会得到false
,但我无法弄清楚差异在哪里。我可以更聪明地使用[9]
选择正确的方法并以这种方式执行,但我也想知道为什么崩溃的版本会这样做。有什么想法吗?编辑:现在有更好的示例:interface BaseInterface
{ }
interface MyInterface : BaseInterface
{ }
abstract class Abstract : MyInterface
{ }
class Concrete : Abstract, MyInterface
{ }
class ProblemClass<GenericType> where GenericType : BaseInterface
{
public virtual IList<Entity> ProblemMethod<Entity>() where Entity : class, GenericType
{
if (typeof(Entity) == typeof(Concrete))
{
MethodInfo methodInfo = System.Reflection.MethodBase.GetCurrentMethod() as MethodInfo;
var t1 = this.GetType(); // perhaps the problem resides in
var t2 = methodInfo.DeclaringType; // these two not being equal?
methodInfo = methodInfo.MakeGenericMethod(typeof(Abstract));
return (methodInfo.Invoke(this, new Object[] { }) as IList).OfType<Entity>().ToList();
}
else
{
return new List<Entity>();
}
}
}
class Program
{
static void Main(string[] args)
{
new ProblemClass<MyInterface>().ProblemMethod<Concrete>();
}
}