【发布时间】:2010-05-10 11:15:56
【问题描述】:
背景
在 .NET 2.0 中工作 这里,一般反映列表。我最初使用t.IsAssignableFrom(typeof(IEnumerable)) 来检测我正在遍历的属性是否支持IEnumerable 接口。 (因此我可以安全地将对象投射到它上面)
但是,当对象是 BindingList<T> 时,此代码不会计算为 True。
下一步
我尝试使用t.IsSubclassOf(typeof(IEnumerable)),但也没有任何运气。
代码
/// <summary>
/// Reflects an enumerable (not a list, bad name should be fixed later maybe?)
/// </summary>
/// <param name="o">The Object the property resides on.</param>
/// <param name="p">The Property We're reflecting on</param>
/// <param name="rla">The Attribute tagged to this property</param>
public void ReflectList(object o, PropertyInfo p, ReflectedListAttribute rla)
{
Type t = p.PropertyType;
//if (t.IsAssignableFrom(typeof(IEnumerable)))
if (t.IsSubclassOf(typeof(IEnumerable)))
{
IEnumerable e = p.GetValue(o, null) as IEnumerable;
int count = 0;
if (e != null)
{
foreach (object lo in e)
{
if (count >= rla.MaxRows)
break;
ReflectObject(lo, count);
count++;
}
}
}
}
意图
我想基本上用ReflectedListAttribute 标记我想反映的列表,并在拥有它的属性上调用这个函数。 (已经工作)
一旦进入这个函数,给定属性所在的对象,以及相关的PropertyInfo,获取属性的值,将其转换为 IEnumerable(假设它是可能的),然后遍历每个子对象并调用 @987654329 @ 在带有 count 变量的孩子上。
【问题讨论】:
标签: c# .net reflection .net-2.0 ienumerable