C # reflection lists: object does not match target type
Trying to add a class object to a list using reflection, but when calling the Add method with my class object as a parameter, I get "Object does not match target type"
Here's a code snippet (you can guess classString = "Processor"
)
PC fetched = new PC();
// Get the appropriate computer field to write to
FieldInfo field = fetched.GetType().GetField(classString);
// Prepare a container by making a new instance of the reffered class
// "CoreView" is the namespace of the program.
object classContainer = Activator.CreateInstance(Type.GetType("CoreView." + classString));
/*
classContainer population code
*/
// This is where I get the error. I know that classContainer is definitely
// the correct type for the list it being added to at this point.
field.FieldType.GetMethod("Add").Invoke(fetched, new[] {classContainer});
Then this is part of the class, the above code adds classContainers to:
public class PC
{
public List<Processor> Processor = new List<Processor>();
public List<Motherboard> Motherboard = new List<Motherboard>();
// Etc...
}
+3
source to share
2 answers
This method will add a new item to the whole list // just instead of using insert Add
IList list = (IList)value;// this what you need to do convert ur parameter value to ilist
if (value == null)
{
return;//or throw an excpetion
}
Type magicType = value.GetType().GetGenericArguments()[0];//Get class type of list
ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);//Get constructor reference
if (magicConstructor == null)
{
throw new InvalidOperationException(string.Format("Object {0} does not have a default constructor defined", magicType.Name.ToString()));
}
object magicClassObject = magicConstructor.Invoke(new object[] { });//Create new instance
if (magicClassObject == null)
{
throw new ArgumentNullException(string.Format("Class {0} cannot be null.", magicType.Name.ToString()));
}
list.Insert(0, magicClassObject);
list.Add(magicClassObject);
0
source to share