解惑

解己之惑,解人之惑

反射获取集合中指定下标的元素

不废话了,直接上代码吧:

public static object GetElementFromCollection(object obj, int index)
{
Type type = obj.GetType();
if (type.IsArray)
{
return ((Array) obj).GetValue(index);
}
else
{
object[] attributes = type.GetCustomAttributes(typeof(DefaultMemberAttribute), true);
DefaultMemberAttribute attribute = (DefaultMemberAttribute) attributes[0];
String indexerName = attribute.MemberName;
type.GetProperties();
PropertyInfo pi2 = type.GetProperty(indexerName, new Type[] { typeof(int) });
return pi2.GetValue(obj, new Object[] {index});
}
}

(Visited 602 times, 1 visits today)

2 Comments

  1. java?
    我还是学习中

  2. 呵呵,C#

Cherami进行回复 取消回复

邮箱地址不会被公开。 必填项已用*标注

© 2024 解惑

本主题由Anders Noren提供向上 ↑