Hello,
I'm trying to deserialize my objects (which derive from CollectionBase)
using the special constructor. Everything works fine until I go to set the
value. I get the following error:
"Object type cannot be converted to target type."
The property Value of newField = 'ArrayList' and val also shows as
ArrayList'.
What could be wrong?
public MyCollection(SerializationInfo info, StreamingContext context)
{
Type entityType = this.GetType();
string fieldName = string.Empty;
foreach (SerializationEntry entry in info)
{
fieldName = entry.Name;
if (fieldName.IndexOf('+') > -1 )
{
string []names = fieldName.Split('+');
string baseType = names[0];
fieldName = names[1];
while (entityType.Name != baseType)
entityType = entityType.BaseType;
}
else
entityType = this.GetType();
MemberInfo []members = entityType.GetMember(fieldName,
MemberTypes.Field, BindingFlags.NonPublic |
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (members.Length > 0)
{
FieldInfo newField = members[0] as FieldInfo;
object val = entry.Value;
if (val != null)
{
if (!newField.FieldType.IsInstanceOfType(val) )
val = Convert.ChangeType(val, newField.FieldType);
}
try
{
// throws error - "Object type cannot be converted to target type."
newField.SetValue(entry, val);
}
catch (Exception ex)
{
int stop = 0;
}
}
}
}
Many thanks,
Joe