繁体   English   中英

从对象实例和PropertyInfo获取列表引用

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM