Are*_*ren 1 .net c# reflection ienumerable .net-2.0
背景
在.NET 2.0中工作在这里,反映一般的列表.我最初t.IsAssignableFrom(typeof(IEnumerable))用来检测我正在遍历的属性是否支持IEnumerable接口.(因此我可以安全地将物体投射到它)
但是这个代码没有True在对象是a时进行评估BindingList<T>.
下一个
我试图使用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++;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
意图
我想基本上标记我想要反映的列表,ReflectedListAttribute并在具有它的属性上调用此函数.(已经工作)
一旦进入这个函数,给定属性所在的对象,并且PropertyInfo相关的,获取属性的值,将其转换为IEnumerable(假设它是可能的),然后遍历每个子节点并ReflectObject(...)使用count变量调用子节点.
Jen*_*und 11
当你这样做as IEnumerable并且变量不为null时,你知道它确实实现了IEnumerable接口.
你不需要代码:
Type t = p.PropertyType;
//if (t.IsAssignableFrom(typeof(IEnumerable)))
if (t.IsSubclassOf(typeof(IEnumerable)))
{
Run Code Online (Sandbox Code Playgroud)
这就足够了:
public void ReflectList(object o, PropertyInfo p, ReflectedListAttribute rla)
{
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++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6118 次 |
| 最近记录: |