ج # - انعكاس باستخدام Generics: مشكلة مع مجموعات متداخلة من المحللين
-
16-09-2019 - |
سؤال
أرغب في أن أكون قادرا على طباعة خصائص الكائنات، وقد أصبت بعقبة عندما تضغط على مجموعات متداخلة من إيلريين.
foreach (PropertyInformation p in properties)
{
//Ensure IList type, then perform recursive call
if (p.PropertyType.IsGenericType)
{
// recursive call to PrintListProperties<p.type?>((IList)p," ");
}
يمكن لأي شخص أن تقدم بعض المساعدة؟
هتافات
كا
المحلول
أنا فقط أفكر بصوت عال هنا. ربما يمكنك الحصول على طريقة طباعة غير عامة غير عامة تبدو مثل هذا:
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()
سوف تعطيك مجموعة من الحجج من النوع. (في حالة THS، مع عنصر واحد فقط، ر في 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)));
لا تنتمي إلى StackOverflow