反思,收藏,词典哦,我的!

时间:2010-11-22 14:26:42

标签: c# generics reflection collections

我在使用反射和访问集合时遇到了一些问题:

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]'。

1 个答案:

答案 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();