【问题标题】:Why can't I find the GetEnumerator() method on the IList type through reflection?为什么通过反射找不到IList类型的GetEnumerator()方法?
【发布时间】:2011-05-25 17:35:39
【问题描述】:

这个代码当然是有效的。根据定义,IList 有一个 GetEnumerator() 方法。

System.Collections.IList list = new List<string>();
System.Collections.IEnumerator ienum = list.GetEnumerator();

但是,以下没有一个能够找到名为 GetEnumerator 的 IList 类型的成员。

Type iListType= typeof(System.Collections.IList);
var member = iListType.GetMember("GetEnumerator");
var members = iListType.GetMembers().Where(x => x.Name == "GetEnumerator");
var method = iListType.GetMethod("GetEnumerator");
var methods = iListType.GetMethods().Where(x => x.Name == "GetEnumerator");

【问题讨论】:

    标签: c# .net reflection types ilist


    【解决方案1】:

    IList 类型上找不到GetEnumerator,因为IList 类型没有声明GetEnumeratorIList 扩展了声明它的 IEnumerable。因此,您需要更改代码以在 IEnumerable 类型上查找 GetEnumerator

    Type type = typeof(System.Collections.IEnumerable);
    var member = type.GetMember("GetEnumerator");
    

    【讨论】:

      【解决方案2】:

      不知道为什么不能为接口已实现的接口查找成员。但要解决此使用:

      var member = iListType.GetInterfaces().Union(new Type[] { iListType }).SelectMany(t => t.GetMember("GetEnumerator"));
      

      您的代码使用类类型而不是接口类型。这很奇怪。我用System.Collections.ArrayList检查了它,它返回了一个方法。

      【讨论】:

      • 我知道。但是,我不确定为什么我们没有一种简单的(可能是使用BindingFlags)方法来查找在基本接口类型中定义的方法。
      【解决方案3】:

      它是IEnumerable 的成员。

      【讨论】:

        【解决方案4】:

        在这种情况下您可能需要设置BindingFlags

        试试这个...

        MemberInfo[] member = iListType.GetMember("GetEnumerator", BindingFlags.Public);            
        

        【讨论】:

        • 错了。 BindingFlags 参数的默认值为BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,其中包括BindingFlags.Public
        猜你喜欢
        • 2012-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多