2010-11-22 58 views
0

我使用反射和訪問集合具有有點問題:反思,收藏,字典哦,我的!

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

你能詳細說一下嗎?你想達到什麼目的,你的代碼是做什麼的,你到底在哪裏得到錯誤信息?人們會很樂意在這裏幫助你,但請不要只是轉儲代碼和錯誤信息,並期望有人爲你進行調試...... – Heinzi 2010-11-22 14:31:03

回答

2

您測試如果ICollection非通用版本被物體implementend和hapilly嘗試將其轉換爲ICollection<Object> ......

無論是測試如果對象真正落實ICollection<Object>

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

或使用類似

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