反思、收藏、词典 天哪!
我在使用反射和访问集合时遇到了一些问题:
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 ]'。
I am having a bit of a problem using reflection and accessing 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;
}
Unable to cast object of type 'ValueCollection[System.String,Axiom.Core.MovableObject]' to type 'System.Collections.Generic.ICollection`1[System.Object]'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您测试
ICollection
的非通用版本是否由对象实现,并乐意尝试将其强制转换为ICollection
要么测试该对象是否真正实现 < code>ICollection
或使用类似的东西
You test if the non generic version of
ICollection
is implementend by an object and hapilly try to cast it toICollection<Object>
...Either test if the object really implement
ICollection<Object>
:or use something like