【问题标题】:Error invoking an extension method using reflection使用反射调用扩展方法时出错
【发布时间】:2010-09-20 18:18:45
【问题描述】:

我收到 InvalidOperationException 的消息:

“不能对 ContainsGenericParameters 为真的类型或方法执行后期绑定操作。”

以下是相关部分代码:

// Gets the entity type of the table to update.
Type entityType = Jobs.GetType(syncSettings.TableToUpdate);

// Creates a generic list with the same type to hold the records to update.
Type listType = typeof(List<>).MakeGenericType(entityType);
object recordsToUpdate = Activator.CreateInstance(listType);

// Fills the list recordsToUpdate...
// A few lines below, I try to call the extension method ElementAt:
MethodInfo elementAtMethod = typeof(Enumerable).GetMethod("ElementAt", BindingFlags.Static | BindingFlags.Public);
elementAtMethod.MakeGenericMethod(entityType);

object record = elementAtMethod.Invoke(
                                     recordsToUpdate,
                                     new object[] { recordsToUpdate, recordIndex });

在我的最后一个动作中,抛出了上面提到的异常。我究竟做错了什么?这个错误是什么意思?

我一直在调查,似乎方法参数类型 T 仍然是通用的。这就是 ContainsGenericParameters 为真的原因。如何将参数设置为 entityType?

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    简单地说,你还没有捕捉到MakeGenericMethod 的结果(它返回一个不同 MethodInfo 代表关闭 方法)

    elementAtMethod = elementAtMethod.MakeGenericMethod(entityType);
    

    但是,我是否建议在大多数情况下使用非泛型IList 更容易,而回退到非泛型IEnumerable(反射和泛型不是好朋友):

    IList list = recordsToUpdate as IList;
    if(list != null) return list[recordIndex];
    // fallback to IEnumerable
    if(recordIndex < 0) throw new IndexOutOfRangeException();
    IEnumerable enumerable = (IEnumerable)recordsToUpdate;
    foreach (object item in enumerable) {
        if (recordIndex-- == 0) return item;
    }
    throw new IndexOutOfRangeException();
    

    (请注意,您不必使用备用代码,因为您始终使用实现了IListList&lt;T&gt;

    【讨论】:

    • 没错!这很有意义,因为 MakeGenericMethod 方法返回 MethodInfo 而不是 void。谢谢@Marc Gravell!
    • @Fabio - 请在IList 上查看我的观点;反射/泛型方法比仅仅转换到 IList 慢得多
    • 是的,我知道反射很慢,但我被告知这不是问题,因为我正在编写的方法仅用于工作者角色。我所做的目标是它变得通用并且无论发生什么变化都可以继续工作,但是您所说的对我来说非常有意义,并感谢您。我一定会考虑到的。感谢您的解决方案和最佳选择。你拯救了我的一天!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多