开发者

Why can't I find the GetEnumerator() method on the IList type through reflection?

This code is of course valid. IList by definition, has a GetEnumerator() method.

System.Collections.IList list = new List<string>();
System.Collecti开发者_Go百科ons.IEnumerator ienum = list.GetEnumerator();

However none of the following are able to find a member of the IList type with the name GetEnumerator.

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");


You can't find GetEnumerator on the IList type, because the IList type does not declare GetEnumerator. IList extends IEnumerable which declares it. So you need to change your code to look for GetEnumerator on the IEnumerable type.

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


It's a member of IEnumerable.


Not sure why you cannot look up for members for interfaces that an interface has implemented. But to workaround this use:

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

You code works with a class type but not an interface type. That is strange. I checked it with System.Collections.ArrayList and it returned one method.


Possibly you need to set BindingFlags in this case.

Try This...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜