[英]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. 但是我不能使用
PropertyInfo.GetValue
来获取列表引用,因为列表具有索引属性,它会引发TargetParameterCountException
。
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.
您不能只获取indexed属性,因为indexed属性可以返回任意多个值之一,或者甚至可以随时使它们返回。
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()
通过有条件地通过其
GetEnumerator()
处理IEnumerable<T>
对象的情况,可以使此操作更容易
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.