调用MethodBase.GetCurrentMethod方法获取泛型类型的泛型方法结果

3

我有一个通用类中的通用方法。在这个方法内部,如果该方法的泛型参数类型未映射,但其父类型映射了,则需要调用相同的父类型方法。然而,对于这两段代码,我得到了不同的结果,尽管我希望它们是相同的。

这个成功:

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>();
    }
}

如果没有最基本的代码知识,很难弄清楚正在发生什么。请展示一个简短但完整的程序(您不需要9个方法),以演示该问题。 - Jon Skeet
当然。有时候,如果有人看到了类似的东西,那就足够了,但我会发布一个更长的例子。 - Becca Dee
1个回答

3
所以问题在于声明类型是一个开放的泛型,而泛型方法中的约束取决于类型中的泛型类型参数。
以下代码解决了这个问题:
MethodInfo methodInfo = System.Reflection.MethodBase.GetCurrentMethod() as MethodInfo;
methodInfo = this.GetType().GetMethod(methodInfo.Name, methodInfo.GetParameters().Select(p => p.ParameterType).ToArray());
methodInfo = methodInfo.MakeGenericMethod(typeof(Abstract));
return (methodInfo.Invoke(this, new Object[] { }) as IList).OfType<Entity>().ToList();

请参阅http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx中的说明。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接