简体   繁体   中英

Getting List reference from object instance and PropertyInfo

I have an instance of a unknown object and I am iterating through it's properties, I must retrieve each instance of each property, currently this is my solution:

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));
                }
            }
        }
    }
}

But I can't use PropertyInfo.GetValue to get the list reference because it throws TargetParameterCountException since the list has an indexed property.

How can I retrieve the list instance?

In order to get an indexes property, you would need to know the types requested and all possible entries of each type, including which ones may or may not be present or throw an exception. You can't just get the indexed property, because an indexed property can return one of any number of values, or even just make them on the fly.

When dealing with a list, it may be best to simple ignore the indexed property and instead copy the underlying data by hand. This can be made easier by conditionally handling cases of IEnumerable<T> objects via their GetEnumerator()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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