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

时间:2013-04-30 15:06:01

标签: .net system.reflection

我在泛型类中有一个泛型方法。在这个方法中,如果方法的泛型参数的类型没有映射,我需要为父类型调用相同的方法,但是父类型。对于两位代码,我得到了不同的结果,但我希望它们是相同的。

这成功了:

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

1 个答案:

答案 0 :(得分: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中的评论。