[英]C# - Reflection using Generics: Problem with Nested collections of ILists
我希望能夠打印對象屬性,當我點擊iList的嵌套集合時遇到了一個障礙。
foreach (PropertyInformation p in properties)
{
//Ensure IList type, then perform recursive call
if (p.PropertyType.IsGenericType)
{
// recursive call to PrintListProperties<p.type?>((IList)p," ");
}
任何人都可以提供幫助嗎?
干杯
K A
我只是在這里大聲想。 也許您可以有一個非通用的PrintListProperties方法,看起來像這樣:
private void PrintListProperties(IList list, Type type)
{
//reflect over type and use that when enumerating the list
}
然后,當您遇到嵌套列表時,請執行以下操作:
if (p.PropertyType.IsGenericType)
{
PringListProperties((Ilist)p,p.PropertyType.GetGenericArguments()[0]);
}
再說一次,還沒有測試過,但是給它一個旋轉...
foreach (PropertyInfo p in props)
{
// We need to distinguish between indexed properties and parameterless properties
if (p.GetIndexParameters().Length == 0)
{
// This is the value of the property
Object v = p.GetValue(t, null);
// If it implements IList<> ...
if (v != null && v.GetType().GetInterface("IList`1") != null)
{
// ... then make the recursive call:
typeof(YourDeclaringClassHere).GetMethod("PrintListProperties").MakeGenericMethod(v.GetType().GetInterface("IList`1").GetGenericArguments()).Invoke(null, new object[] { v, indent + " " });
}
Console.WriteLine(indent + " {0} = {1}", p.Name, v);
}
else
{
Console.WriteLine(indent + " {0} = <indexed property>", p.Name);
}
}
p.PropertyType.GetGenericArguments()
將為您提供類型參數的數組。 (在這種情況下,只有一個元素,即IList<T>
)
var dataType = myInstance.GetType();
var allProperties = dataType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var listProperties =
allProperties.
Where(prop => prop.PropertyType.GetInterfaces().
Any(i => i == typeof(IList)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.