【问题标题】:Refelection , Collections, Dictonaries Oh My!反射、收藏、字典 Oh My!
【发布时间】:2023-04-09 22:30:01
【问题描述】:

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

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]”类型。

【问题讨论】:

标签: c# generics reflection collections


【解决方案1】:

您测试ICollection 的非通用版本是否由对象实现,并尝试将其强制转换为ICollection&lt;Object&gt; ...

要么测试对象是否真的实现了ICollection&lt;Object&gt;

private bool isCollection(object o)
{
    return o is ICollection<object>;
}

或使用类似的东西

rCollection = ((IEnumerable)prop.GetValue(obj, null)).OfType<Object>().ToList();

【讨论】:

    猜你喜欢
    • 2018-07-10
    • 2015-06-20
    • 1970-01-01
    • 2015-12-23
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    相关资源
    最近更新 更多