尝试使用反射将类对象添加到List中,但是当使用我的类对象作为参数调用Add方法时,我得到'对象与目标类型不匹配'
以下是我们关注的代码段(您现在可以假设为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's being added to at this point.
field.FieldType.GetMethod("Add").Invoke(fetched, new[] {classContainer});
然后,这是上述代码将classContainers添加到类的一部分:
public class PC
{
public List<Processor> Processor = new List<Processor>();
public List<Motherboard> Motherboard = new List<Motherboard>();
// Etc...
}
答案 0 :(得分:4)
您尝试在List.Add(Processor)
上致电PC
- 您想在字段的值上调用:
field.FieldType.GetMethod("Add").Invoke(field.GetValue(fetched),
new[] {classContainer});
但是,我个人建议您不拥有这样的公共字段。请考虑使用属性。
答案 1 :(得分:0)
此方法将新项目添加到所有列表//而不是插入使用添加
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);