[英]Getting List reference from object instance and PropertyInfo
我有一個未知對象的實例,並且要遍歷它的屬性,我必須檢索每個屬性的每個實例,目前這是我的解決方案:
private static void WriteMembers(object arg, XmlWriter writer, object[] attributes)
{
foreach (var property in arg.GetType().GetProperties())
{
if (attributes.All(x => x.GetType() != typeof (XmlIgnoreAttribute)))
{
if (property.GetIndexParameters().Length > 0)
{
//how to get list reference?
}
else
{
var value = property.GetValue(arg, null);
if (value != null)
{
WriteMember(value, property.Name, writer, property.GetCustomAttributes(false));
}
}
}
}
}
但是我不能使用PropertyInfo.GetValue
來獲取列表引用,因為列表具有索引屬性,它會引發TargetParameterCountException
。
如何檢索列表實例?
為了獲得索引屬性,您需要知道請求的類型以及每種類型的所有可能的條目,包括可能存在或可能不存在或引發異常的條目。 您不能只獲取indexed屬性,因為indexed屬性可以返回任意多個值之一,或者甚至可以隨時使它們返回。
處理列表時,最好簡單地忽略索引屬性,而手動復制基礎數據。 通過有條件地通過其GetEnumerator()
處理IEnumerable<T>
對象的情況,可以使此操作更容易
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.