【发布时间】: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]”类型。
【问题讨论】:
-
你能详细说明一下吗?你想达到什么目标,你的代码做了什么,你到底在哪里得到错误信息?人们很乐意在这里为您提供帮助,但请不要只是转储代码和错误消息并期望有人为您调试它...
-
Insted of "o.GetType().GetInterface("ICollection") != null" 您可以使用“o is ICollection”或“o as ICollection”。见msdn.microsoft.com/en-us/library/scekt9xw%28VS.71%29.aspx 和msdn.microsoft.com/en-us/library/cscsdfbt%28v=VS.71%29.aspx
标签: c# generics reflection collections