我在使用反射和访问集合时遇到了一些问题:
XmlElement xmlObject = Scene.CreateElement("Object");
Type Target = obj.GetType();
... xml code here
PropertyInfo[] props = Target.GetProperties(BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.Static);
foreach (PropertyInfo prop in props)
{
Type propType = prop.PropertyType;
if ((propType.IsPublic && propType.IsValueType && prop.CanRead && prop.CanWrite)
|| PropertyNameExceptions.Contains(prop.Name)
|| PropertyTypeExceptions.Contains(prop.PropertyType.Name))
{
object result = null;
try
{
result = prop.GetValue(obj, null);
}
catch
{
}
}
else if (isCollection(result))
{
Type pType = result.GetType();
PropertyInfo[] pTypeInfo = pType.GetProperties();
ICollection<object> rCollection = null;
try
{
rCollection = (ICollection<object>)prop.GetValue(obj, null);
}
catch
{
}
foreach (object o in rCollection)
{
ObjectToXML(o, xmlPropertyObject);
}
}
}
private bool isCollection(object o)
{
if (o.GetType().GetInterface("ICollection") != null)
{
return true;
}
return false;
}
无法将类型为'ValueCollection [System.String,Axiom.Core.MovableObject]'的对象强制转换为'System.Collections.Generic.ICollection`1 [System.Object]'。
答案 0 :(得分:2)
您测试一个对象是否实现了ICollection
的非泛型版本,并尝试将其强制转换为ICollection<Object>
...
测试对象是否真正实现ICollection<Object>
:
private bool isCollection(object o)
{
return o is ICollection<object>;
}
或使用类似
的内容rCollection = ((IEnumerable)prop.GetValue(obj, null)).OfType<Object>().ToList();